Find a line in a file and remove it

后端 未结 16 1858
谎友^
谎友^ 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条回答
  •  Happy的楠姐
    2020-11-22 13:34

    Here is the complete Class. In the below file "somelocation" refers to the actual path of the file.

    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);
        }
    
    }
    

提交回复
热议问题