我需要幫助才能刪除並重命名Java編程中的文件。我的問題是原始文件無法刪除,第二個文件無法重命名。以下是代碼片段。任何建議,將不勝感激。在Java編程中刪除並重命名文件
import java.awt.event.*;
import java.io.*;
import java.util.ArrayList;
import java.util.Scanner;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.*;
public void deleteLine(String content) {
try {
File inFile = new File("football.dat");
if (!inFile.isFile()) {
System.out.println("Parameter is not an existing file");
return;
}
File tempFile = new File(inFile.getAbsolutePath() + "2");
BufferedReader br = new BufferedReader(new FileReader(inFile));
PrintWriter pw = new PrintWriter(new FileWriter(tempFile), true);
String linetobeempty = null;
while ((linetobeempty = br.readLine()) != null) {
if (!linetobeempty.trim().equals(content)) {
pw.println(linetobeempty);
pw.flush(); System.out.println(linetobeempty);
}
}
pw.close();
br.close();
boolean b = inFile.delete();
if (!b) {
System.out.println("Could not delete file");
return;
}
//Rename the new file to the filename the original file had.
if (!tempFile.renameTo(inFile)) {
System.out.println("Could not rename file");
}
} catch (FileNotFoundException ex) {
ex.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
}
}
什麼問題? – 2012-04-14 19:22:19
什麼是錯誤? – Spoike 2012-04-14 19:28:47
要創建臨時文件,您應該使用File.createTempFile(字符串前綴,字符串後綴,文件目錄)。沒有必要在每一行書寫行後都調用'pw.flush();'。通常在close()之前調用它就足夠了。你應該確保你的流被關閉,把關閉放到finally塊中,否則你可能無法刪除或刪除文件。例如'try {...} ffinally {close(pw); close(br);}'其中close是靜態方法,比如'static void close(Reader r){if(r!= null)try {r.close(); } catch(Exception e){// log}}' – andih 2012-04-14 19:33:43