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

edit, java, text-files

Solution

A quick test confirmed that not closing the writer as I wrote in my comment above actually produces the behavior you describe.

Just add

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

to your `finally` block, and your program works.

Problem

``` 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's name to old file name File newFile = new File(tmpFileName); newFile.renameTo(oldFile); ``` When running the code above I end up with an empty file "tmpfiles.txt" and the file "files.txt is being deleted. can anyone help? I don't want to use a string to read the file. I would prefer to do it his way.

Original source