The following simple java method implements a simple way to remove a set of consecutive lines from a text file.

It can be used to:

  • remove first n lines from a text file
  • remove last n lines from a text file
  • remove lines from n to m in a text file

To do the work, the deleteLines method uses the getNumberOfLines method I explained in how to count the number of lines

Here you are the source of the method:

    void deleteLines(String filename, int startline, int numlines) {
        try {
            StringBuilder sb;
            //String buffer to store contents of the file
            try (BufferedReader br = new BufferedReader(new FileReader(filename))) {
                //String buffer to store contents of the file
                sb = new StringBuilder("");
                //Keep track of the line number
                int linenumber = 1;
                String line;
                while ((line = br.readLine()) != null) {
                    //Store each valid line in the string buffer
                    if (linenumber < startline || linenumber >= startline + numlines) {
                        sb.append(line).append("\n");
                    }
                    linenumber++;
                }
                if (startline + numlines > linenumber) {
                    System.out.println("End of file reached.");
                }
            }

            try (FileWriter fw = new FileWriter(new File(filename + ".head"))) {
                //Write entire string buffer into the file
                fw.write(sb.toString());
            }
        } catch (IOException e) {
            System.out.println(e.getMessage());
        }
    }

 

To use the method just use the following calls:

deleteLines(textFilePath, 1, 33); // removes first 33 lines
deleteLines(textFilePath, 10, 100); // removes lines from 10 to 100
deleteLines(textFilePath, getNumberOfLines(textFilePath)-33, getNumberOfLines(textFilePath)); // removes last 33 lines 

Gg1