Find a line in a file and remove it

后端 未结 16 1840
谎友^
谎友^ 2020-11-22 13:06

I\'m looking for a small code snippet that will find a line in file and remove that line (not content but line) but could not find. So for example I have in a file following

相关标签:
16条回答
  • 2020-11-22 13:53
    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 讨论(0)
  • 2020-11-22 13:57
        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();
        }
      }
    

    This I have found on the internet.

    0 讨论(0)
  • 2020-11-22 13:58

    You want to do something like the following:

    • Open the old file for reading
    • Open a new (temporary) file for writing
    • Iterate over the lines in the old file (probably using a BufferedReader)
      • For each line, check if it matches what you are supposed to remove
      • If it matches, do nothing
      • If it doesn't match, write it to the temporary file
    • When done, close both files
    • Delete the old file
    • Rename the temporary file to the name of the original file

    (I won't write the actual code, since this looks like homework, but feel free to post other questions on specific bits that you have trouble with)

    0 讨论(0)
  • 2020-11-22 14:00

    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);
    
    0 讨论(0)
提交回复
热议问题