Find the line in the file and delete it

I am looking for a small piece of code that will find a line in a file and delete that line (not content, but line), but could not find. So, for example, I have the following file:

Myfile.txt

aaa bbb ccc ddd 

You need to have this function: public void removeLine(String lineContent) , and if I removeLine("bbb") , I get the file as follows:

Myfile.txt:

 aaa ccc ddd 
+56
java file editing
Sep 04 '09 at 4:50
source share
16 answers

This solution may not be optimal or beautiful, but it works. It reads line by line in the input file, writing each line to a temporary output file. Whenever he encounters a string that matches what you are looking for, it skips writing this. Then it renames the output file. I missed error handling, closing readers / writers, etc. From an example. I also assume that the line you are looking for does not have a leading or trailing space. Change the code around trim () as needed to find a match.

 File inputFile = new File("myFile.txt"); File tempFile = new File("myTempFile.txt"); BufferedReader reader = new BufferedReader(new FileReader(inputFile)); BufferedWriter writer = new BufferedWriter(new FileWriter(tempFile)); String lineToRemove = "bbb"; String currentLine; while((currentLine = reader.readLine()) != null) { // trim newline when comparing with lineToRemove String trimmedLine = currentLine.trim(); if(trimmedLine.equals(lineToRemove)) continue; writer.write(currentLine + System.getProperty("line.separator")); } writer.close(); reader.close(); boolean successful = tempFile.renameTo(inputFile); 
+76
Sep 04 '09 at 5:08
source share
  public void removeLineFromFile(String file, String lineToRemove) { try { File inFile = new File(file); if (!inFile.isFile()) { System.out.println("Parameter is not an existing file"); return; } //Construct the new file that will later be renamed to the original filename. File tempFile = new File(inFile.getAbsolutePath() + ".tmp"); BufferedReader br = new BufferedReader(new FileReader(file)); PrintWriter pw = new PrintWriter(new FileWriter(tempFile)); String line = null; //Read from the original file and write to the new //unless content matches data to be removed. while ((line = br.readLine()) != null) { if (!line.trim().equals(lineToRemove)) { pw.println(line); pw.flush(); } } pw.close(); br.close(); //Delete the original file if (!inFile.delete()) { System.out.println("Could not delete file"); return; } //Rename the new file to the filename the original file had. if (!tempFile.renameTo(inFile)) System.out.println("Could not rename file"); } catch (FileNotFoundException ex) { ex.printStackTrace(); } catch (IOException ex) { ex.printStackTrace(); } } 

I found this on the Internet.

+24
Sep 04 '09 at 19:13
source share

You want to do something like the following:

  • Open the old file for reading
  • Open a new (temporary) file for writing
  • Iterating over the lines in the old file (possibly using BufferedReader )
    • For each row, check if it matches what you have to delete.
    • If it matches, do nothing
    • If it does not match, write it to a temporary file
  • When finished, close both files.
  • Delete old file
  • Rename the temporary file to the name of the source file

(I won’t write the actual code, since it looks like homework, but feel free to post other questions about specific bits that you have problems with)

+20
Sep 04 '09 at 5:09
source share

Using apache commons-io and Java 8, you can use

  List<String> lines = FileUtils.readLines(file); List<String> updatedLines = lines.stream().filter(s -> !s.contains(searchString)).collect(Collectors.toList()); FileUtils.writeLines(file, updatedLines, false); 
+16
Feb 22 '15 at 13:19
source share

Therefore, when I hear someone mention that he wants to filter the text, I immediately think about going to Streams (mainly because there is a method called filter that filters exactly as you need). Another answer mentions using Stream with the Apache commons-io library, but I thought it would be wise to show how this can be done in standard Java 8. Here is the simplest form:

 public void removeLine(String lineContent) throws IOException { File file = new File("myFile.txt"); List<String> out = Files.lines(file.toPath()) .filter(line -> !line.contains(lineContent)) .collect(Collectors.toList()); Files.write(file.toPath(), out, StandardOpenOption.WRITE, StandardOpenOption.TRUNCATE_EXISTING); } 

I think that there is not much to explain, basically Files.lines receives Stream<String> lines of the file, filter Files.lines lines that we don’t need, and then collect puts all the lines of the new file in the List . Then we write the list on top of the existing file using Files.write , using the optional TRUNCATE option to replace the old contents of the file.

Of course, this approach has a flip side: loading each line into memory, since they are all stored in a List before being written back. If we wanted to just change without saving, we would need to use some form of OutputStream to write each new line to the file when it passes through the stream, for example:

 public void removeLine(String lineContent) throws IOException { File file = new File("myFile.txt"); File temp = new File("_temp_"); PrintWriter out = new PrintWriter(new FileWriter(temp)); Files.lines(file.toPath()) .filter(line -> !line.contains(lineContent)) .forEach(out::println); out.flush(); out.close(); temp.renameTo(file); } 

In this example, little has changed. In fact, instead of using the collect command to collect the contents of the file into memory, we use forEach so that each line passing through the filter sent to PrintWriter for immediate writing to the file and not saved. We must save it to a temporary file because we cannot overwrite the existing file at the same time that we are still reading from it, so at the end we rename the temporary file to replace the existing file.

+9
Aug 20 '17 at 16:06 on
source share

Here you go. This solution uses a DataInputStream to scan the position of the string you want to replace, and uses the FileChannel to replace the text at that exact position. It replaces only the first occurrence of the found string. This solution does not store somewhere a copy of the entire file (or RAM, or a temporary file), it simply edits the part of the file that it finds.

 public static long scanForString(String text, File file) throws IOException { if (text.isEmpty()) return file.exists() ? 0 : -1; // First of all, get a byte array off of this string: byte[] bytes = text.getBytes(/* StandardCharsets.your_charset */); // Next, search the file for the byte array. try (DataInputStream dis = new DataInputStream(new FileInputStream(file))) { List<Integer> matches = new LinkedList<>(); for (long pos = 0; pos < file.length(); pos++) { byte bite = dis.readByte(); for (int i = 0; i < matches.size(); i++) { Integer m = matches.get(i); if (bytes[m] != bite) matches.remove(i--); else if (++m == bytes.length) return pos - m + 1; else matches.set(i, m); } if (bytes[0] == bite) matches.add(1); } } return -1; } public static void replaceText(String text, String replacement, File file) throws IOException { // Open a FileChannel with writing ability. You don't really need the read // ability for this specific case, but there it is in case you need it for // something else. try (FileChannel channel = FileChannel.open(file.toPath(), StandardOpenOption.WRITE, StandardOpenOption.READ)) { long scanForString = scanForString(text, file); if (scanForString == -1) { System.out.println("String not found."); return; } channel.position(scanForString); channel.write(ByteBuffer.wrap(replacement.getBytes(/* StandardCharsets.your_charset */))); } } 

example

Input: ABCDEFGHIJKLMNOPQRSTUVWXYZ

Method call:

 replaceText("QRS", "000", new File("path/to/file"); 

Result File: ABCDEFGHIJKLMNOP000TUVWXYZ

+3
Jul 05 '18 at 12:26
source share
  public static void deleteLine() throws IOException { RandomAccessFile file = new RandomAccessFile("me.txt", "rw"); String delete; String task=""; byte []tasking; while ((delete = file.readLine()) != null) { if (delete.startsWith("BAD")) { continue; } task+=delete+"\n"; } System.out.println(task); BufferedWriter writer = new BufferedWriter(new FileWriter("me.txt")); writer.write(task); file.close(); writer.close(); } 
+2
Apr 07 '17 at 13:46 on
source share

Here is the full class. In the file below, "somelocation" refers to the actual file path.

 import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; public class FileProcess { public static void main(String[] args) throws IOException { File inputFile = new File("C://somelocation//Demographics.txt"); File tempFile = new File("C://somelocation//Demographics_report.txt"); BufferedReader reader = new BufferedReader(new FileReader(inputFile)); BufferedWriter writer = new BufferedWriter(new FileWriter(tempFile)); String currentLine; while((currentLine = reader.readLine()) != null) { if(null!=currentLine && !currentLine.equalsIgnoreCase("BBB")){ writer.write(currentLine + System.getProperty("line.separator")); } } writer.close(); reader.close(); boolean successful = tempFile.renameTo(inputFile); System.out.println(successful); } } 
+1
Jan 31 '15 at 3:54
source share
 public static void deleteLine(String line, String filePath) { File file = new File(filePath); File file2 = new File(file.getParent() + "\\temp" + file.getName()); PrintWriter pw = null; Scanner read = null; FileInputStream fis = null; FileOutputStream fos = null; FileChannel src = null; FileChannel dest = null; try { pw = new PrintWriter(file2); read = new Scanner(file); while (read.hasNextLine()) { String currline = read.nextLine(); if (line.equalsIgnoreCase(currline)) { continue; } else { pw.println(currline); } } pw.flush(); fis = new FileInputStream(file2); src = fis.getChannel(); fos = new FileOutputStream(file); dest = fos.getChannel(); dest.transferFrom(src, 0, src.size()); } catch (IOException e) { e.printStackTrace(); } finally { pw.close(); read.close(); try { fis.close(); fos.close(); src.close(); dest.close(); } catch (IOException e) { e.printStackTrace(); } if (file2.delete()) { System.out.println("File is deleted"); } else { System.out.println("Error occured! File: " + file2.getName() + " is not deleted!"); } } } 
0
Sep 12 '14 at 2:31
source share
 package com.ncs.cache; import java.io.BufferedReader; import java.io.FileReader; import java.io.File; import java.io.FileWriter; import java.io.FileNotFoundException; import java.io.IOException; import java.io.PrintWriter; public class FileUtil { public void removeLineFromFile(String file, String lineToRemove) { try { File inFile = new File(file); if (!inFile.isFile()) { System.out.println("Parameter is not an existing file"); return; } // Construct the new file that will later be renamed to the original // filename. File tempFile = new File(inFile.getAbsolutePath() + ".tmp"); BufferedReader br = new BufferedReader(new FileReader(file)); PrintWriter pw = new PrintWriter(new FileWriter(tempFile)); String line = null; // Read from the original file and write to the new // unless content matches data to be removed. while ((line = br.readLine()) != null) { if (!line.trim().equals(lineToRemove)) { pw.println(line); pw.flush(); } } pw.close(); br.close(); // Delete the original file if (!inFile.delete()) { System.out.println("Could not delete file"); return; } // Rename the new file to the filename the original file had. if (!tempFile.renameTo(inFile)) System.out.println("Could not rename file"); } catch (FileNotFoundException ex) { ex.printStackTrace(); } catch (IOException ex) { ex.printStackTrace(); } } public static void main(String[] args) { FileUtil util = new FileUtil(); util.removeLineFromFile("test.txt", "bbbbb"); } } 

src: http://www.javadb.com/remove-a-line-from-a-text-file/

0
Mar 01 '15 at 5:10
source share

This solution requires adding the Apo Commons IO library to the build path. It works by reading the entire file and writing each line back, but only if the search query is not contained.

 public static void removeLineFromFile(File targetFile, String searchTerm) throws IOException { StringBuffer fileContents = new StringBuffer( FileUtils.readFileToString(targetFile)); String[] fileContentLines = fileContents.toString().split( System.lineSeparator()); emptyFile(targetFile); fileContents = new StringBuffer(); for (int fileContentLinesIndex = 0; fileContentLinesIndex < fileContentLines.length; fileContentLinesIndex++) { if (fileContentLines[fileContentLinesIndex].contains(searchTerm)) { continue; } fileContents.append(fileContentLines[fileContentLinesIndex] + System.lineSeparator()); } FileUtils.writeStringToFile(targetFile, fileContents.toString().trim()); } private static void emptyFile(File targetFile) throws FileNotFoundException, IOException { RandomAccessFile randomAccessFile = new RandomAccessFile(targetFile, "rw"); randomAccessFile.setLength(0); randomAccessFile.close(); } 
0
Apr 27 '15 at 12:22
source share

I reorganized the solution that Narek had to create (for me) with a somewhat more efficient and understandable code. I used the built-in automatic resource management, a recent Java feature and used the Scanner class, which is easier for me to understand and use.

Here is the code with the edited comments:

 public class RemoveLineInFile { private static File file; public static void main(String[] args) { //create a new File file = new File("hello.txt"); //takes in String that you want to get rid off removeLineFromFile("Hello"); } public static void removeLineFromFile(String lineToRemove) { //if file does not exist, a file is created if (!file.exists()) { try { file.createNewFile(); } catch (IOException e) { System.out.println("File "+file.getName()+" not created successfully"); } } // Construct the new temporary file that will later be renamed to the original // filename. File tempFile = new File(file.getAbsolutePath() + ".tmp"); //Two Embedded Automatic Resource Managers used // to effectivey handle IO Responses try(Scanner scanner = new Scanner(file)) { try (PrintWriter pw = new PrintWriter(new FileWriter(tempFile))) { //a declaration of a String Line Which Will Be assigned Later String line; // Read from the original file and write to the new // unless content matches data to be removed. while (scanner.hasNextLine()) { line = scanner.nextLine(); if (!line.trim().equals(lineToRemove)) { pw.println(line); pw.flush(); } } // Delete the original file if (!file.delete()) { System.out.println("Could not delete file"); return; } // Rename the new file to the filename the original file had. if (!tempFile.renameTo(file)) System.out.println("Could not rename file"); } } catch (IOException e) { System.out.println("IO Exception Occurred"); } } } 
0
Aug 27 '16 at 11:22
source share

Try the following:

 public static void main(String[] args) throws IOException { File file = new File("file.csv"); CSVReader csvFileReader = new CSVReader(new FileReader(file)); List<String[]> list = csvFileReader.readAll(); for (int i = 0; i < list.size(); i++) { String[] filter = list.get(i); if (filter[0].equalsIgnoreCase("bbb")) { list.remove(i); } } csvFileReader.close(); CSVWriter csvOutput = new CSVWriter(new FileWriter(file)); csvOutput.writeAll(list); csvOutput.flush(); csvOutput.close(); } 
0
Mar 28 '17 at 11:04 on
source share

An old question, but an easy way is this:

  • Iterate over a file, add each line to a new list of arrays
  • iterate over the array, find the appropriate string, then call the delete method.
  • repeat the array again, printing each line in the file, the boolean value for append should be false, which basically replaces the file
0
Jul 04 '18 at 6:39
source share

This solution uses RandomAccessFile to cache only the portion of the file following the line to be deleted. It scans until it finds the String you want to delete. Then he copies all the data after the found line, then writes it over the found line and everything after. Finally, it truncates the file size to remove extra data.

 public static long scanForString(String text, File file) throws IOException { if (text.isEmpty()) return file.exists() ? 0 : -1; // First of all, get a byte array off of this string: byte[] bytes = text.getBytes(/* StandardCharsets.your_charset */); // Next, search the file for the byte array. try (DataInputStream dis = new DataInputStream(new FileInputStream(file))) { List<Integer> matches = new LinkedList<>(); for (long pos = 0; pos < file.length(); pos++) { byte bite = dis.readByte(); for (int i = 0; i < matches.size(); i++) { Integer m = matches.get(i); if (bytes[m] != bite) matches.remove(i--); else if (++m == bytes.length) return pos - m + 1; else matches.set(i, m); } if (bytes[0] == bite) matches.add(1); } } return -1; } public static void remove(String text, File file) throws IOException { try (RandomAccessFile rafile = new RandomAccessFile(file, "rw");) { long scanForString = scanForString(text, file); if (scanForString == -1) { System.out.println("String not found."); return; } long remainderStartPos = scanForString + text.getBytes().length; rafile.seek(remainderStartPos); int remainderSize = (int) (rafile.length() - rafile.getFilePointer()); byte[] bytes = new byte[remainderSize]; rafile.read(bytes); rafile.seek(scanForString); rafile.write(bytes); rafile.setLength(rafile.length() - (text.length())); } } 

Using:

File Content: ABCDEFGHIJKLMNOPQRSTUVWXYZ

Method call: remove("ABC", new File("Drive: /Path/File.extension"));

Resulting Content: DEFGHIJKLMNOPQRSTUVWXYZ

This solution can be easily modified for deletion with a specific, specific cacheSize parameter if there is a cacheSize memory problem. This will simply include iterating over the rest of the file to constantly replace parts of the size, cacheSize . In any case, this solution is usually much better than caching the entire file in memory or copying it to a temporary directory, etc.

0
Dec 18 '18 at 5:43
source share

This solution reads the line of the input file line by line, writing each line to the StringBuilder variable. Whenever he encounters a string that matches what you are looking for, he skips writing it. It then deletes the contents of the file and places the contents of the StringBuilder variable.

 public void removeLineFromFile(String lineToRemove, File f) throws FileNotFoundException, IOException{ //Reading File Content and storing it to a StringBuilder variable ( skips lineToRemove) StringBuilder sb = new StringBuilder(); try (Scanner sc = new Scanner(f)) { String currentLine; while(sc.hasNext()){ currentLine = sc.nextLine(); if(currentLine.equals(lineToRemove)){ continue; //skips lineToRemove } sb.append(currentLine).append("\n"); } } //Delete File Content PrintWriter pw = new PrintWriter(f); pw.close(); BufferedWriter writer = new BufferedWriter(new FileWriter(f, true)); writer.append(sb.toString()); writer.close(); } 
0
Jul 11 '19 at 13:18
source share



All Articles