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();
}
}
무엇이 문제입니까? –
무엇이 오류입니까? – Spoike
임시 파일을 만들려면'File.createTempFile (문자열 접두어, 문자열 접미사, 파일 디렉토리)를 사용해야합니다. 모든 p 든 행 다음에'pw.flush();'를 호출 할 필요가 없습니다. 보통'close()'전에 호출하는 것으로 충분합니다. 스트림이 닫히는 지 확인하고 finally 블록에 닫기를 넣어야합니다. 그렇지 않으면 파일을 삭제하거나 제거하지 못할 수 있습니다. 예를 들어'try {...} ffinally {close (pw); close (br);}'close는 정적 static close (Reader r)와 같은 정적 메소드입니다. if (r! = null) try {r.close(); } catch (Exception e) {// log}}' – andih