Search code examples
javafileparsing

java program to conditionally read lines from file


I'm new to coding in Java. I put together this piece of code to read all lines between the "Start" and "End" tag in the following text file.

Start

hi

hello

how

are

you

doing?

End

My program is as follows....

package test;

import java.io.*;

public class ReadSecurities {
public static int countLines(String filename) throws IOException {
    InputStream is = new BufferedInputStream(new FileInputStream(filename));
    try {
        byte[] c = new byte[1024];
        int count = 0;
        int readChars = 0;
        boolean empty = true;
        while ((readChars = is.read(c)) != -1) {
            empty = false;
            for (int i = 0; i < readChars; ++i) {
                if (c[i] == '\n') {
                    ++count;
                }
            }
        }
        return (count == 0 && !empty) ? 1 : count;
    } finally {
        is.close();
    }
}

public static void main(String[] args) {
    // TODO Auto-generated method stub

      try {
        FileInputStream in = new FileInputStream("U:\\Read101.txt");
        FileOutputStream out = new FileOutputStream("U:\\write101.txt");
    BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(out));
      BufferedReader br = new BufferedReader(new InputStreamReader(in));

        for (int i=1; i<=countLines("U:\\Read101.txt"); i++) {
            String line=br.readLine();
                 while (line.contains("Start")) {
                    for (int j=i; j<=countLines("U:\\Read101.txt"); j++) {
                        String line2=br.readLine();
                        System.out.println(line2);
                        if(line2.contains("End")) break; 
                    else {
                             bw.write(line2);
                             bw.newLine();
                    }
                        bw.close();
                    } break;
                 }
               }
            br.close();
      }
      catch (Exception e) { }
      finally { }
      }
}

The program reads only the first two lines "hi hello" as though the if condition does not exist. I have a feeling the mistake is very basic, but please correct me.


Solution

  • String line;
    
    do{ line = br.readLine(); }
    while( null != line && !line.equals("Start"));
    
    if ( line.equals("Start") ) { // in case of EOF before "Start" we have to skip the rest!
        do{ 
            line = br.readLine(); 
            if ( line.equals("End") ) break;
            // TODO write to other file
        }while(null != line )
    }
    

    Should be as easy as that. I left out creation / destruction of resources and proper Exception handling for brevity.

    But please do at least log exceptions!

    EDIT:

    If EOF is encountered before Start, you have to skip the copy step!