Javaプログラミングでファイルを削除して名前を変更する際に助けが必要です。私の問題は、元のファイルを削除することはできませんし、2番目のファイルの名前を変更することはできません。ここにスニペットコードを示します。どんな提案もありがとうございます。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(文字列接頭辞、文字列接尾辞、ファイルディレクトリ)を使用する必要があります。書かれた行のたびに '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