简体   繁体   中英

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

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.

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM