How can I delete a specific string in a text file?
Asked
Active
Viewed 3.7k times
1
-
2What do you have so far, and how doesn't it work? – Ignacio Vazquez-Abrams Mar 19 '11 at 05:07
1 Answers
23
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:

BalusC
- 1,082,665
- 372
- 3,610
- 3,555
-
+1 - though it is a bit more complicated if the String you are trying to delete spans line boundaries. – Stephen C Mar 19 '11 at 08:04
-
It is so tedious, why is it quicker in SQL. quick to scan through but time consuming to edit. – kyle england Sep 28 '15 at 19:59
-
3