在本地写入保存的操作, 很多时候我们习惯使用Outputstream, 而其实写文本文件的时候, Java提供一个很好的工具给我们 ----- writer. 由于它是针对文本类型的文件操作, 所以如果是对TXT, LOG等这类文本文件进行写操作时, 它的效率比Outputstream高不少. 以下是一个栗子.
public static void main(String[] args) { OutputStreamWriter ops = null; BufferedWriter bw = null; File file; File newFile; String jsonStr2="hello world"; try { String name="文件名称"; file = new File("D:/workspace/存放路径1",name + ".txt"); newFile = new File("D:/workspace/存放路径2", name +".new"); newFile.createNewFile(); ops = new OutputStreamWriter(new FileOutputStream(file), "UTF-8"); bw = new BufferedWriter(ops); bw.append(jsonStr2); } catch (Exception e) { e.printStackTrace(); } finally { try { if (bw != null) { bw.flush(); bw.close(); } } catch (Exception e) { e.printStackTrace(); } } }
writer的flush 和 close操作必须放在finally那里, 因为进行读写操作时, 数据先读取到缓存中, 再从缓存中读取写入文件. 因此从缓冲区读完数据后, 必须flush清空缓冲区, 然后close关闭读写流.