Passing data from one txt to another txt

Asked

Viewed 191 times

2

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

test.txt

 João,Maria,José

In my class I take the file and pass 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 pick up some positions from array and save in another .txt that would be the gerado.txt (emptiness).

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?

1 answer

5


You have two objects referencing the same file, there are no technical problems in it, but the way it is in your code besides unnecessary led you to make a logical mistake because you try to write through the Printwriter object but you do not give flush in it (the flush makes all the information that is in the buffer are effectively written to your archive).

The method close() calls the method flush() before effectively closing the resource, however you are calling the method close() in his another object, the object you have not entered any information, so your file is empty at the end of the execution of your program. Therefore, the solution is you call the method close() (or you can also call the method flush()) in the even object you write.

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.