Reputation: 41
I am trying to write to and write to files through the following code snippet. However the file is created but nothing is written in it. I have already tested the lines structure and it is ok.
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();
}
Upvotes: 1
Views: 84
Reputation: 58
You have some flaws in your code:
BufferedWriter
Following code should fix your problem:
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();
}
The try with resources calls the AutoCloseable#close()
method after it leaves the try-catch
block. And whenever close()
is called. The BufferedWriter
also invokes flush()
which finally writes to your file.
Upvotes: 4