Search code examples
javafileblank-line

How can I ignore a blank line in a srt file using Java


I have a srt file like below and I want to remove blank line : in line no 3

**
1
Line1: 00:00:55,888 --> 00:00:57,875.  
Line2:Antarctica  
Line3:   
Line4:2  
Line5:00:00:58,375 --> 00:01:01,512  
Line6:An inhospitable wasteland.    
**
        FileInputStream fin = new FileInputStream("line.srt");
        FileOutputStream fout = new FileOutputStream("m/line.srt");
        int i = 0;
        while(((i =fin.read()) != -1)){
            if(i != 0)
            fout.write((byte)i);
        }

Solution

  • There you go. Steps:

    1) FileInputStream fin = new FileInputStream("line.srt"); this is to get the file to a bufferedreader in the next step

    2) BufferedReader reader = new BufferedReader(new InputStreamReader(fin)); get the text file to a buffereader

    3) PrintWriter out = new PrintWriter("newline.srt"); use a print writer to write the string of every line in the new text file

    4) String line = reader.readLine(); read next line

    5) while(line != null){ if (!line.trim().equals("")) { check that line is not null and that line is not empty

    6) out.println(line); write line (not empty) to the output .srt file

    7) line = reader.readLine(); get new line

    8) out.close(); close PrintWriter in the end...

    import java.io.*;
    class RemoveBlankLine {
        public static void main(String[] args) throws FileNotFoundException, IOException{
            FileInputStream fin = new FileInputStream("line.srt");
            BufferedReader reader = new BufferedReader(new InputStreamReader(fin));
            PrintWriter out = new PrintWriter("newline.srt");
            int i = 0;
            String line = reader.readLine();
            while(line != null){
                        if (!line.trim().equals("")) {
                            out.println(line);
                        }
                        line = reader.readLine();
                    }    
                out.close();
        }
    }
    

    INPUT:

    **
    1
    00:00:55,888 --> 00:00:57,875.  
    Antarctica  
    
    2  
    00:00:58,375 --> 00:01:01,512  
    An inhospitable wasteland.    
    **
    

    OUTPUT:

    **
    1
    00:00:55,888 --> 00:00:57,875.  
    Antarctica  
    2  
    00:00:58,375 --> 00:01:01,512  
    An inhospitable wasteland.    
    **
    

    By the way, make sure you are clear when you ask your questions, because the way you state your problem I assumed Line1, Line2, etc are part of your input file, and I have prepared another solution which I had to change... Make sure you are clear and precise so that you get the proper answers !