removing extra white spaces from text files

user3001418 picture user3001418 · Jun 17, 2014 · Viewed 14.4k times · Source

I have number of text files in the following format:

196903274115371008    @266093898 

Prince George takes his first public steps with his mom,                              Catherine, Duchess of    

Cambridge.

I would like to remove all extra while spaces + new line characters except the first new line characters. So I would like to above to be like this:

196903274115371008@266093898 

Prince George takes his first public steps with his mom, Catherine, Duchess of Cambridge.

I wrote the following code :

package remove_white_space222;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;


public class Remove_white_space222 {

    public static void main(String[] args) throws FileNotFoundException, IOException {

        FileReader fr = new FileReader("input.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
            line=line.replaceAll("\\s+", " ");
            fw.write(line);


        }
        fr.close();
        fw.close();
    }

}

Thanks in advance for your help,,,,

Answer

Aarati Sakhare picture Aarati Sakhare · Mar 2, 2020
    File file = new File("input_file.txt");
    try(BufferedReader br = new BufferedReader(new FileReader(file)); 
            FileWriter fw = new FileWriter("empty_file.txt")) {
        String st;
        while((st = br.readLine()) != null){
            fw.write(st.replaceAll("\\s+", " ").trim().concat("\n"));
        }
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }