OCJP

Java Program to Remove Blank Lines from a Text File

Hereby we demonstrate an example for Removing Blank Lines from a give Text File in Java using File Management.

import java.io.*;
import java.util.ArrayList;
public class RemoveBlankLine{

public static void main(String []a){

if(a.length != 1){
	System.out.println("Please Enter Path of File with File Name");
return;
}
File file=null;
try{

file = new File(a[0]);
if(!file.exists()){
System.out.println("File Does not Exists");
return;
}

FileInputStream fins= new FileInputStream(file);
byte []bytes= new byte[fins.available()];
fins.read(bytes);
fins.close();
String data= new String(bytes);
System.out.println(data);

String []lines= data.split("\n");

int ln=1;
ArrayList<String>noblanklines= new ArrayList<String>();

for(String line:lines){
//	System.out.println((ln++) +" "+line);
if(line.trim().length()!=0)
{
	noblanklines.add(line.trim());
}
}
System.out.println("Total Lines :"+ noblanklines.size());
File newfile=new File("newfile.txt");
FileOutputStream fouts = new FileOutputStream(newfile);

for(String line:noblanklines){
	line= "\n"+line;
	fouts.write(line.getBytes());
}
fouts.close();
}catch(Exception e){
e.printStackTrace();
}
}
}

We have used FileInputStream class for getting the content of the File. FileOutputStream is used to create a new file.

Leave a Reply

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


× How can I help you?