我在編輯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聲明,但不確定如何使用它? 這些文件位於程序文件夾中,我計劃使它可移植,因此當程序在不同的計算機上使用時目錄會有所不同,因此我認爲每次路徑會有所不同。
您似乎是從文件中刪除所有換行符。我永遠不會忽略一個異常,特別是在代碼中,它不會做我認爲應該做的事情。在刪除/重命名代碼被調用之前,您確定沒有收到錯誤嗎? –
永不淺的例外:你寫了'catch(IOException ex){/ *從來沒有任何東西* /}'。將其更改爲catch(IOException ex){ex.printStackTrace();你會知道更多。 – zloster
@JSmithers在catch塊中添加一個日誌。你可能想要檢查文件是否真的被刪除了。 – chaitanya