【发布时间】:2016-04-23 01:39:30
【问题描述】:
我使用缓冲区阅读器解析整个文件。如果找到 Oranges: 模式,我想用 ApplesAndOranges 替换它。
try (BufferedReader br = new BufferedReader(new FileReader(resourcesFilePath))) {
String line;
while ((line = br.readLine()) != null) {
if (line.startsWith("Oranges:")){
int startIndex = line.indexOf(":");
line = line.substring(startIndex + 2);
String updatedLine = "ApplesAndOranges";
updateLine(line, updatedLine);
我调用一个方法 updateLine 并传递我的原始行以及更新后的行值。
private static void updateLine(String toUpdate, String updated) throws IOException {
BufferedReader file = new BufferedReader(new FileReader(resourcesFilePath));
PrintWriter writer = new PrintWriter(new File(resourcesFilePath+".out"), "UTF-8");
String line;
while ((line = file.readLine()) != null)
{
line = line.replace(toUpdate, updated);
writer.println(line);
}
file.close();
if (writer.checkError())
throw new IOException("Can't Write To File"+ resourcesFilePath);
writer.close();
}
要更新文件,我必须用不同的名称保存它(resourcesFilePath+".out")。如果我使用原始文件名,保存的版本将变为空白。
所以这是我的问题,如何在不丢失任何数据的情况下用原始文件中的任何值替换一行。
【问题讨论】:
-
读取每一行,处理它,写入一个新文件。完成后,删除旧文件并将新文件重命名到它的位置
-
你需要用新行重写文件。你不能使用 line.replace
-
感谢 MadProgrammer 的输入。我使用了 Array
- 来重写数据。我不确定这是否是过度杀戮,因为我只需要替换该资源文件中的一行。请发布您的评论作为答案以相应地接受它。您能否确认在不重写整个文件的情况下无法替换该行?
标签: java bufferedreader filewriter