我正在尝试通过以下代码片段写入和写入文件。但是,该文件已创建,但其中并未写入任何内容。我已经测试了lines结构,它是正常的。
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();
}
发布于 2018-06-02 03:32:30
您的代码中有一些缺陷:
你永远不会刷新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 with resources在离开try-catch
块后调用AutoCloseable#close()
方法。无论何时调用close()
。BufferedWriter
还会调用flush()
,它最终会写入您的文件。
https://stackoverflow.com/questions/50649948
复制相似问题