removing extra white spaces from text files

16,904
    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();
    }
Share:
16,904
user3001418
Author by

user3001418

Updated on June 22, 2022

Comments

  • user3001418
    user3001418 about 2 years

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

    • TheLostMind
      TheLostMind about 10 years
      +1 for the clean code and explaination of what you want.. Seldom seen on SOF.
    • Bentaye
      Bentaye over 4 years
      Will the second line always be blank in all your input files?