我正在尝试将自己的txt写入特定目录中的文件。 test.mod文件已正确放置,但是当我打开文件时它是空的并且不包含任何文本。 我在这里想念的是什么?
public static void main(String[] args) { String pad = "C:\\Users\\Bernard\\Documents\\Paradox Interactive"; File bestand = new File(pad + "\\test.mod"); try { BufferedWriter pen = new BufferedWriter(new FileWriter(bestand)); pen.write("line1"); pen.write("line2"); }catch(IOException e){ } }感谢您的时间
I am having my first go at trying to write my own txt to a a file ,in a specific directory. The test.mod file is correctly placed ,but when I open up the file it is empty and contains no text. What am I missing here?
public static void main(String[] args) { String pad = "C:\\Users\\Bernard\\Documents\\Paradox Interactive"; File bestand = new File(pad + "\\test.mod"); try { BufferedWriter pen = new BufferedWriter(new FileWriter(bestand)); pen.write("line1"); pen.write("line2"); }catch(IOException e){ } }Thank you for your time
最满意答案
当您写入BufferedWriter您(可能)写入内存缓冲区,并且必须flush()写入以确保它们到达磁盘。 close()也会在任何合理的实现上隐式调用flush() ,但依赖它并不是一个好习惯:
public static void main(String[] args) { String pad = "C:\\Users\\Bernard\\Documents\\Paradox Interactive"; File bestand = new File(pad + "\\test.mod"); BufferedWriter pen = null; try { pen = new BufferedWriter(new FileWriter(bestand)); pen.write("line1"); pen.write("line2"); pen.flush(); }catch(IOException e){ // Probably should have some treatment here too } finally { if (pen != null) { pen.close(); } } }When you write to a BufferedWriter you are (potentially) writing to an in-memory buffer, and you must flush() your writes to make sure they reach the disk. close() would also implicitly call flush() on any reasonable implementation, but it isn't considered a good practice to rely on it:
public static void main(String[] args) { String pad = "C:\\Users\\Bernard\\Documents\\Paradox Interactive"; File bestand = new File(pad + "\\test.mod"); BufferedWriter pen = null; try { pen = new BufferedWriter(new FileWriter(bestand)); pen.write("line1"); pen.write("line2"); pen.flush(); }catch(IOException e){ // Probably should have some treatment here too } finally { if (pen != null) { pen.close(); } } }更多推荐
发布评论