How to remove blank lines from a text file in Java

Hi, today’s tutorial is about how to remove blank lines from a text file in Java.

Imagine, you have a huge text file running into thousands and thousands of characters with a lot of blank lines in the middle. What if you had to delete the blank lines and compile the whole text file with zero line separators (blank lines). Deleting each line manually would be a cumbersome task and will waste a lot of time. Hence, we need something that will do this instantly for us.

Untitled.txt

Hello

world


this

is 



a 



Java

tutorial

You should learn: Reading A Text File Line By Line In Java With Example

How to read a specific line from a text file in Java

Program: remove blank lines from a text file in Java

The following Java code will do the needful for us. Let us check how.

package linedeleter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.Scanner;
import java.util.logging.Level;
import java.util.logging.Logger;

class RemoveBlankLine {
  public static void main(String[] args) {

        Scanner file;
        PrintWriter writer;

        try {

            file = new Scanner(new File("/Users/ayushsanghavi/Desktop/Untitled.txt")); //sourcefile
            writer = new PrintWriter("/Users/ayushsanghavi/Desktop/Untitled2.txt"); //destinationfile

            while (file.hasNext()) {
                String line = file.nextLine();
                if (!line.isEmpty()) {
                    writer.write(line);
                    writer.write("\n");
                }
            }

            file.close();
            writer.close();

        } catch (FileNotFoundException ex) {
            Logger.getLogger(RemoveBlankLine.class.getName()).log(Level.SEVERE, null, ex);
        }
}
}

Let us try it out.

Output file

Untitled2.txt

Hello
world
This
is 
a
Java
tutorial

You can try this on your IDE.

You can also check out Count Number Of Occurrences Of A Word In A Text File In Java

Leave a Reply

Your email address will not be published. Required fields are marked *