4
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.

Jacob Schoen
  • 14,034
  • 15
  • 82
  • 102
ECEMartina
  • 43
  • 3
  • 8
    You never close your Writer, that might be the problem. – Keppil Nov 21 '12 at 14:45
  • 1
    side note: `if (line.contains("Smokey")) line = line.replace("Smokey;","AAAAAA;");` You appear to have 2 extra semicolons – tckmn Nov 21 '12 at 14:48

3 Answers3

3

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.

Keppil
  • 45,603
  • 8
  • 97
  • 119
1

I found some issue in your code.

First, this line seems not correct:

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 should flush and close the bw after finish it.

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

Correct me if I'm wrong.

Thinhbk
  • 2,194
  • 1
  • 23
  • 34
0

The file is never written to because the writer was never "flushed". When closing the writer all the data in the buffer is automatically written to the file. Get used to standards with streams where you close them in a try-catch block.

Thomas
  • 650
  • 9
  • 9