Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

removing extra white spaces from text files

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,,,,

like image 596
user3001418 Avatar asked Nov 11 '22 06:11

user3001418


1 Answers

    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();
    }
like image 199
Aarati Sakhare Avatar answered Nov 15 '22 06:11

Aarati Sakhare