Passing data from one txt to another txt

2

I have a .txt file with three comma-separated names, in this case:

test.txt

 João,Maria,José

In my class I get the file and step to a array , separating by comma:

String nomeArquivo="teste.txt";
String nomeArquivoGerado="gerado.txt";
String linha = "";
String linha2[];

try {
    FileReader reader = new FileReader(nomeArquivo);
    BufferedReader leitor = new BufferedReader(reader);
    linha=leitor.readLine();
    linha2=linha.split(",");

I want to get some positions of array and save in another .txt that would be gerado.txt (empty).

FileWriter writer = new FileWriter(nomeArquivoGerado);
PrintWriter gravarArquivo = new PrintWriter(nomeArquivoGerado);
gravarArquivo.printf(linha2[0]).print(linha2[1]);
writer.close();

Can anyone tell me what I'm doing wrong?

    
asked by anonymous 30.10.2014 / 17:19

1 answer

5

You have two objects referencing the same file, there are no technical issues with that, but the way it is in your code is unnecessary, and it has led you to make a logic error because you try to write through the PrintWriter object, but you do not flush in it ( flush ) causes all the information that is in the buffer to be effectively written to your file.

The close() method calls the flush() method before actually closing the resource, however you are calling the close() method on your other object, the object that you did not enter any information , so your file is empty at the end of your program's execution. So the solution is you call the close() method (or you can also call the flush() method) on the same object you write.

The differences between FileWriter and PrintWriter are few, basically PrintWriter has some methods that FileWriter does not have, such as print() and println() . Both have the write() and append() methods. Just choose one of them and delete the other. Regardless of which class you choose to work on, do flush after entering the information in it.

    
30.10.2014 / 17:27