How to delete a specific string in a text file?

2019-01-23 22:26发布

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

标签: java file-io
1条回答
走好不送
2楼-- · 2019-01-23 22:53

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:

查看更多
登录 后发表回答