Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
184 views
Welcome To Ask or Share your Answers For Others

1 Answer

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:


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...