8

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!

Mat
  • 202,337
  • 40
  • 393
  • 406
Shumon Saha
  • 1,415
  • 6
  • 16
  • 33

8 Answers8

14

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

Afshin Moazami
  • 2,092
  • 5
  • 33
  • 55
JJ.
  • 5,425
  • 3
  • 26
  • 31
4

Have a look at trim() function

http://docs.oracle.com/javase/1.5.0/docs/api/java/lang/String.html#trim()

Also, some code would be helpful...

Afshin Moazami
  • 2,092
  • 5
  • 33
  • 55
Trefex
  • 2,290
  • 16
  • 18
  • 1
    That the only valid solution which is already emdedded in the String object. There is absolutely no need to do anything else. This should be set as the answer – Omri Oct 11 '15 at 12:14
  • 2
    `Returns a copy of the string, with leading and trailing whitespace omitted.` It does not remove whitespace within the text file, only leading & trailing. This is not what the OP asked for. OP wants to remove all spaces and tabs. – Kevin Van Ryckegem Mar 05 '16 at 02:44
3
...
Scanner scanner = new Scanner(new File("infile.txt"));
PrintStream out = new PrintStream(new File("outfile.txt"));
while(scanner.hasNextLine()){
    String line = scanner.nextLine();
    line = line.trim();
    if(line.length() > 0)
        out.println(line);
}
...
umbr
  • 440
  • 2
  • 4
1

This my first time answering to a question in this site so please be understandable, after a lot of searching I have found this that works for me.

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

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

Remove spaces for each line and do not consider empty and null lines:

String line =  buffer.readLine();

while (line != null) {
    line = removeSpaces(line);        
    //ignore empty lines
    if (line.isEmpty()) return;

      ....code....


    line =  buffer.readLine();
} 




public String removeSpaces (String arg)
{
    Pattern whitespace = Pattern.compile("\\s");
    Matcher matcher = whitespace.matcher(arg);
    String result = "";
    if (matcher.find()) {
        result = matcher.replaceAll("");
    }
    return result;
}
Diego Ocampo
  • 143
  • 8
0

Used to remove empty lines in same the file.

public static void RemoveEmptyLines(String FilePath) throws IOException
{
    File inputFile = new File(FilePath);
    BufferedReader reader = new BufferedReader(new FileReader(inputFile));
    String inputFileReader;
    ArrayList <String> DataArray = new ArrayList<String>();
    while((inputFileReader=reader.readLine())!=null)
    {
        if(inputFileReader.length()==0)
        {
            continue;
        }
        DataArray.add(inputFileReader);
    }
    reader.close();

    BufferedWriter bw = new BufferedWriter(new FileWriter(FilePath));
    for(int i=0;i<DataArray.size();i++)
    {
        bw.write(DataArray.get(i));
        bw.newLine();
        bw.flush();
    }
    bw.close();
}
0
package com.home.interview;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class RemoveInReadFile {

    public static void main(String[] args) {

        try {
            Scanner scanner = new Scanner(new File("Readme.txt"));


            while(scanner.hasNext())
            {
                String line = scanner.next();

                String lineAfterTrim = line.trim();
                System.out.print(lineAfterTrim);
            }


        } 

        catch (FileNotFoundException e) {

            e.printStackTrace();
        }

    }

}
  • In this program, I have removed all the white spaces and read everything from the file I read in a single line. – Nagarjun BN Oct 14 '17 at 11:57
0

I think you just want a regex expression:

        txt= txt.replaceAll("\\n\\s*\\n", "\n");  //remove empty lines
        txt= txt.replaceAll("\\s*", "");  //remove whitespaces

As for reading/writing files, there are plenty of other resources to find out how to do that.

john k
  • 6,268
  • 4
  • 55
  • 59