2

テキストファイルの特定の行を更新できるようにしたい。しかし、ファイルを削除できないというエラーが表示されます。なぜこのエラーが発生するのですか?

public class Main {
    public static void main(String[] args) {
        Main rlf = new Main();
        rlf.removeLineFromFile("F:\\text.txt", "bbb");
    }

    public void removeLineFromFile(String file, String lineToRemove) {
        try {
            File inFile = new File(file);

            if (!inFile.isFile()) {
                System.out.println("Parameter is not an existing file");
                return;
            }

            //Construct the new file that will later be renamed to the original filename.
            File tempFile = new File(inFile.getAbsolutePath() + ".tmp");

            BufferedReader br = new BufferedReader(new FileReader(file));
            PrintWriter pw = new PrintWriter(new FileWriter(tempFile));

            String line = null;

            //Read from the original file and write to the new
            //unless content matches data to be removed.
            while ((line = br.readLine()) != null) {

                if (!line.trim().equals(lineToRemove)) {

                    pw.println(line);
                    pw.flush();
                }
            }
            pw.close();
            br.close();

            //Delete the original file
            if (!inFile.delete()) {
                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();
        }
    }
}​
4

4 に答える 4

2

を調べる必要がありますRandomAccessFile

これにより、ファイル内の目的の場所を検索し、更新する部分のみを更新できます。

于 2010-10-07T03:10:30.417 に答える
2

プログラムは私のために働きます。おそらくあなたは環境問題を抱えています。

于 2010-10-07T03:18:39.953 に答える
0

Justinが上で指摘したように、ファイルの一部を変更する場合は、RandomAccessFileの種類のAPIを使用する必要があります。使用しようとしているアプローチには、多くの潜在的な問題があります。

  • さらに、tmpファイルを作成する必要があります。大きなファイルには対応できない場合があります(ただし、問題のドメインはわかりません)
  • ファイルをジャグリングしようとすると、いくつかの潜在的な例外が発生する可能性があり、多くのエラー処理が必要になります。
于 2010-10-07T03:19:52.783 に答える
0

(古いインスタンスを閉じるために)新しいインスタンスを作成し、newそれを使用して削除することができます。ここで
同じファイル削除の問題

于 2010-10-07T03:28:30.890 に答える