How to delete a specific string in a text file?

前端 未结 1 1092
臣服心动
臣服心动 2020-12-16 08:45

How can I delete a specific string in a text file?

相关标签:
1条回答
  • 2020-12-16 09:12

    Locate the file.

    File file = new File("/path/to/file.txt");
    

    Create a temporary file (otherwise you've to read everything into Java's memory first).

    File temp = File.createTempFile("file", ".txt", file.getParentFile());
    

    Determine the charset.

    String charset = "UTF-8";
    

    Determine the string you'd like to delete.

    String delete = "foo";
    

    Open the file for reading.

    BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(file), charset));
    

    Open the temp file for writing.

    PrintWriter writer = new PrintWriter(new OutputStreamWriter(new FileOutputStream(temp), charset));
    

    Read the file line by line.

    for (String line; (line = reader.readLine()) != null;) {
        // ...
    }
    

    Delete the string from the line.

        line = line.replace(delete, "");
    

    Write it to temp file.

        writer.println(line);
    

    Close the reader and writer (preferably in the finally block).

    reader.close();
    writer.close();
    

    Delete the file.

    file.delete();
    

    Rename the temp file.

    temp.renameTo(file);
    

    See also:

    • The Java Tutorials - Lesson: basic I/O
    0 讨论(0)
提交回复
热议问题