[英]File does not seem to be renaming in Java
我在用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語句,但是不確定如何使用它? 這些文件位於program文件夾中,並且我計划使其可移植,以便在其他計算機上使用該程序時目錄會有所不同,因此為什么我認為每次路徑都不同。
下面的代碼對我來說完全正常。 它編輯文件以及刪除文件。
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.txt之后,Members_Temp.txt文件已創建並重命名為Members.txt。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.