[ACCEPTED]-How to delete a specific string in a text file?-file-io

Accepted answer
Score: 22

Locate the file.

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

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

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

Determine the charset.

String charset = "UTF-8";

Determine 7 the string you'd like to delete.

String delete = "foo";

Open the 6 file for reading.

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

Open the temp file for 5 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 4 the string from the line.

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

Write it to temp 3 file.

    writer.println(line);

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

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

Delete the file.

file.delete();

Rename the 1 temp file.

temp.renameTo(file);

See also:

More Related questions