public class WriteReadFiles { private static Logger log = LoggerFactory.getLogger(WriteReadFiles.class); public boolean writeFile(String content) { String filename = "E:/java_src/MVCDemo3/MVCDemo3/accounts.txt"; try { File f = new File(filename); if (!f.exists()) { f.createNewFile(); } OutputStreamWriter write = new OutputStreamWriter(new FileOutputStream(f)); BufferedWriter writer = new BufferedWriter(write); writer.write(content); writer.flush(); write.close(); writer.close(); log.debug("Write File complete!"); return true; }catch (Exception e){ e.printStackTrace(); } return false; }
使用BufferedWriter 将内容写入文件,先开始少了wriite.flush()这句,发现无法写入内容。查资料后发现,原来BufferedWriter是缓冲输入流,意思是当你调用BufferedWriter的write方法时候。数据是先写入到缓冲区里,并没有直接写入到目的文件里。你必须调用BufferedWriter的flush()方法。这个方法会刷新一下该缓冲流,也就是会把数据写入到目的文件里。必须有这句的样子,实践中如果没有writer.flush(); 仅有writer.close();,会报异常。
可参考以下文章理解与文件读写相关的流:http://blog.csdn.net/u013225534/article/details/45727863