Find a line in a file and remove it

后端 未结 16 1852
谎友^
谎友^ 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:37

    This solution requires the Apache Commons IO library to be added to the build path. It works by reading the entire file and writing each line back but only if the search term 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();
    }
    

提交回复
热议问题