我正在尝试通过以下代码片段写入和写入文件。然而,文件已创建,但其中未写入任何内容。我已经测试过线路结构,没问题。
try{
File file = new File("../received/"+nameFiles.get(op-1));
BufferedWriter bw = new BufferedWriter( new FileWriter( file, true ) );
for(String index : lines){
bw.write(index);
System.out.println(index);
}
System.out.println("Arquivo criado");
}catch(IOException ex){
ex.printStackTrace();
}
最佳答案
您的代码存在一些缺陷:
- 你永远不会刷新
BufferedWriter
- 你也永远不会关闭它
以下代码应该可以解决您的问题:
final File file = new File("../received/"+nameFiles.get(op-1));
try(BufferedWriter bw = new BufferedWriter(new FileWriter(file, true) )){
for(String index : lines){
bw.write(index);
System.out.println(index);
}
System.out.println("Arquivo criado");
} catch(IOException ex){
ex.printStackTrace();
}
使用资源的 try 在离开 try-catch
block 后调用 AutoCloseable#close()
方法。每当调用 close()
时。 BufferedWriter
还会调用 flush()
最终写入您的文件。
关于java - BufferedWriter write() 不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50649948/