我在使用Java编辑文本文件中的记录时遇到问题。我能够打印到临时文件,但无法删除主文件并重命名临时文件。
private void editFile(String old, String newLine) throws FileNotFoundException, IOException {
try {
File inFile = new File ("Members.txt");
File tempFile = new File ("Members_Temp.txt");
inFile.setReadable(true);
inFile.setWritable(true);
tempFile.setReadable(true);
tempFile.setWritable(true);
PrintWriter PW;
try (
//Defines the BufferedReader to read the Current File
BufferedReader BR = new BufferedReader(new FileReader(inFile))) {
FileWriter temp = new FileWriter(tempFile);
PW = new PrintWriter (temp);
String line = null;
//While Loop to read the current file till it ends
while ((line = BR.readLine()) != null) {
String replace = old.replace(old, newLine); //Replaces old data with the new data
PW.write(replace); //Writes to the temporary file
//PW.flush();
}
BR.close();
PW.close();
inFile.delete();
tempFile.renameTo(inFile);
}
}
catch (IOException ex) {
}
}
我已经尝试过交换语句,但这看起来也不起作用。我正在考虑Files.move语句但不确定如何使用它? 这些文件位于程序文件夹中,我打算将其设置为可移植,因此当程序在另一台计算机上使用时,目录会有所不同,因此我认为每次路径都不同。
答案 0 :(得分:0)
下面的代码对我来说完全没问题。它编辑文件以及删除文件。
private void editFile(String old, String newLine)
throws FileNotFoundException, IOException {
try {
File inFile = new File("Members.txt");
File tempFile = new File("Members_Temp.txt");
inFile.setReadable(true);
inFile.setWritable(true);
tempFile.setReadable(true);
tempFile.setWritable(true);
PrintWriter PW;
try (
// Defines the BufferedReader to read the Current File
BufferedReader BR = new BufferedReader(new FileReader(inFile))) {
FileWriter temp = new FileWriter(tempFile);
PW = new PrintWriter(temp);
PW.write("");
String line = null;
// While Loop to read the current file till it ends
while ((line = BR.readLine()) != null) {
if (line.contains(old)) {
String replace = line.replace(old, newLine);
PW.append(replace+"\n");
} else
PW.append(line+"\n");
}
BR.close();
PW.close();
inFile.delete();
tempFile.renameTo(inFile);
}
} catch (IOException ex) {
}
}
如何测试?
最初 Members.txt 文件将包含以下条目
ravi
ravindra
devadiga
编辑方法的参数将是“ indra ”和“ dee ”
运行java应用程序后,Members.txt将有以下条目
ravi
ravdee
devadiga
表示已创建Members_Temp.txt文件,并在删除原始Members.txt后重命名为Members.txt