简体   繁体   English

我想编辑文本文件中的部分行

[英]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. 当运行上面的代码时,我最终得到一个空文件“tmpfiles.txt”,文件“files.txt正在删除。有人可以帮忙吗?我不想用字符串来读取文件。我更愿意按他的方式行事。

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. 到你的finally一块,你的程序工作。

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. 而且,你应该在完成之后冲洗并关闭bw。

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. 关闭writer时,缓冲区中的所有数据都会自动写入文件。 Get used to standards with streams where you close them in a try-catch block. 习惯使用在try-catch块中关闭它们的流的标准。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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