我不能写东西给我自己制作的txtfile(I can't write stuff to my self

系统教程 行业动态 更新时间:2024-06-14 16:57:40
我不能写东西给我自己制作的txtfile(I can't write stuff to my self-made txtfile) java

我正在尝试将自己的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(); } } }

更多推荐

本文发布于:2023-04-13 12:38:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/dzcp/cf7009333de21b33c8c28febf8561331.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:给我   东西   txtfile   write   stuff

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!