I want to edit part of a line in a text file

BufferedReader br = null; BufferedWriter bw = null; try { br = new BufferedReader(new FileReader(oldFileName)); bw = new BufferedWriter(new FileWriter(tmpFileName)); String line; while ((line = br.readLine()) != null) { if (line.contains("Smokey")){ line = line.replace("Smokey;","AAAAAA;"); bw.write(line+"\n"); } else { bw.write(line+"\n"); } } } catch (Exception e) { return; } finally { try { if(br != null){ br.close(); messagejLabel.setText("Error"); } } catch (IOException e) { } } // Once everything is complete, delete old file.. File oldFile = new File(oldFileName); oldFile.delete(); // And rename tmp file name to old file name File newFile = new File(tmpFileName); newFile.renameTo(oldFile); 

When I run the code above, I end up with the empty file “tmpfiles.txt” and the file “files.txt is deleted. Can anyone help? I don’t want to use the line to read the file. I would prefer to do it my own way.

+4
source share
3 answers

A quick test confirmed that not closing the writer, as I wrote in my comment above, really causes the behavior you described.

Just add

 if (bw != null) { bw.close(); } 

into your finally block, and your program runs.

+3
source

I found some problem in your code.

Firstly, this line seems wrong:

 if (line.contains("Smokey")){ line = line.replace("Smokey;","AAAAAA;"); bw.write(line+"\n"); 

it should be:

 if (line.contains("Smokey;")){ line = line.replace("Smokey;","AAAAAA;"); bw.write(line+"\r\n"); 

And you have to clean and close bw after completion.

 if (bw != null){ bw.flush(); bw.close(); } 

Correct me if I am wrong.

+1
source

A file is never recorded because the author never blushed. When closing a record, all data in the buffer is automatically written to the file. Get used to the standards with threads, where you close them in a try-catch block.

0
source

Source: https://habr.com/ru/post/1447509/


All Articles