读取文件转为字符串:
//输入文件File类型,输出字符串 public static String fileToString(File file) { InputStream is = null; ByteArrayOutputStream bos = new ByteArrayOutputStream(); byte[] buffer = new byte[1024]; int temp = -1; try { is = new FileInputStream(file); while ((temp = is.read(buffer)) != -1) { bos.write(buffer, 0, temp); } return bos.toString(); } catch (IOException e) { e.printStackTrace(); } finally { try { if(is!=null) { is.close(); } if(bos != null) { bos.close(); } } catch (IOException e) { e.printStackTrace(); } } return null; }
字符串输出为文件
// 字符串输出为文件的方法 // 参数为要输出为文件的字符串,输出路径,及文件名 public static boolean stringToFile(String fileContent, String outPath, String fileName) { boolean result = false; File file = new File(outPath, fileName); OutputStream os = null; try { if (!file.exists()) { file.createNewFile(); } os = new FileOutputStream(file); os.write(fileContent.getBytes()); os.flush(); result = true; } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { try { if(os!=null) { os.close(); } } catch (IOException e) { e.printStackTrace(); } } return result; }
原文:https://www.cnblogs.com/cxylm/p/15090320.html
标签:java,catch,file,字符串,new,null,os From: https://www.cnblogs.com/zhxn/p/18021869