我正在读取文件 in.txt
并将数字写入文件 out.txt
直到找到 42。但是在 out.txt 中我得到空白文件相反,如果我写 System.out.println(num)
而不是 out.write(num)
我会得到正确的结果。这意味着问题出在以下语句上BufferedReader.我哪里错了?
导入java.io.*;
class Numbers
{
public static void main(String args[])
{
try{
String num;
BufferedReader in=new BufferedReader(new FileReader("in.txt"));
BufferedWriter out=new BufferedWriter(new FileWriter("out.txt"));
while((num=in.readLine())!=null)
{
if(Integer.parseInt(num)==42)
break;
else
out.write(num);
}
}catch(Exception e)
{
System.out.println("File not found");
}
}
}
最佳答案
问题是您没有关闭 out
流。将其更改为:
BufferedReader in = null;
BufferedReader out = null;
try{
String num;
in = new BufferedReader(new FileReader("in.txt"));
out = new BufferedWriter(new FileWriter("out.txt"));
while((num=in.readLine())!=null)
{
if(Integer.parseInt(num)==42)
break;
else
out.write(num);
}
out.close()
}catch(Exception e)
{
System.out.println("File not found");
}finally{
try{
if(in!=null) in.close();
if(out!=null) out.close();
}catch(Exception ex) {ex.printStackTrace();}
}
这是因为,您的 OutputStream 会缓冲您的数据并定期刷新它。关闭流不仅会刷新它,而且还可以使其他应用程序安全地使用该文件。
在您的情况下,您可能会遇到奇怪的行为(有时完整写入,有时不写入)。这是因为 BufferedWriter() 尝试在其 finalize
方法(可能会或可能不会被调用)中关闭它
关于java - BufferedWriter 不向文件写入任何内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19122875/