Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove all blank spaces and empty lines

How to remove all blank spaces and empty lines from a txt File using Java SE?

Input:

qwe
    qweqwe
  qwe



qwe

Output:

qwe
qweqwe
qwe
qwe

Thanks!

like image 260
Shumon Saha Avatar asked Aug 25 '11 12:08

Shumon Saha


1 Answers

How about something like this:

FileReader fr = new FileReader("infile.txt"); 
BufferedReader br = new BufferedReader(fr); 
FileWriter fw = new FileWriter("outfile.txt"); 
String line;

while((line = br.readLine()) != null)
{ 
    line = line.trim(); // remove leading and trailing whitespace
    if (!line.equals("")) // don't write out blank lines
    {
        fw.write(line, 0, line.length());
    }
} 
fr.close();
fw.close();

Note - not tested, may not be perfect syntax but gives you an idea/approach to follow.

See the following JavaDocs for reference purposes: http://download.oracle.com/javase/7/docs/api/java/io/FileReader.html http://download.oracle.com/javase/7/docs/api/java/io/FileWriter.html

like image 120
JJ. Avatar answered Nov 03 '22 10:11

JJ.