Dan Quenaz
Dan Quenaz

Reputation: 41

BufferedWriter write() not working

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

Answers (1)

Vifu
Vifu

Reputation: 58

You have some flaws in your code:

  1. You're never flushing the BufferedWriter
  2. You're never closing it either

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

Related Questions