0

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.

MohanVS
  • 167
  • 1
  • 1
  • 10
  • No ditch it completely. Call br.readLine until it returns null. – Fildor Jun 23 '16 at 13:48
  • The loops completely make no sense. And **never** do this: `catch (Exception e) { }`! You will miss exceptions driving you crazy when debugging! And more evil: Driving your fellow devs crazy when they are using your stuff ... – Fildor Jun 23 '16 at 13:51
  • Hello @Berger, i tried storing it in a variable and used it...still the same result. This is the code i used `code` BufferedReader br = new BufferedReader(new InputStreamReader(in)); int sizeoffile=countLines("U:\\Read101.txt"); for (int i=1; i<=sizeoffile; i++) { String line=br.readLine(); while (line.contains("Start")) { for (int j=i; j<=sizeoffile; j++) { String line2=br.readLine(); – MohanVS Jun 23 '16 at 13:56
  • Hello Fildor, The file has content after the end tag as well. I want to read just the lines between Start and End. – MohanVS Jun 23 '16 at 13:58
  • You can break early then. The point was: Don't count the lines. You can do this with 2 while loops (or even less). 1. Read until you read "Start" (or reach EOF) 2. Then after that copy until you read "End" (or EOF) – Fildor Jun 23 '16 at 13:58

3 Answers3

1
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!

Fildor
  • 14,510
  • 4
  • 35
  • 67
  • @MohanVS Note my edit! It occurred to me that if the File should happen to _not_ contain the "Start" element, EOF is reached in the first loop causing an exception in the second. So you have to check for that! – Fildor Jun 24 '16 at 06:52
0

You make one crucial mistake in your code: you don't handle the exceptions correctly. Two things:

  1. never catch Exception. Either catch just one type of Exception or specify a list of exceptions you want to catch. In your case, a simple IOException would suffice.

  2. Never leave a catch-block empty. Either throw a new exception, return a value or - in your case - print the exception with e.printStackTrace().

When you do these two things, you will notice that your code throws an IOException, because you close your bw-Stream too early. Move the bw.close() down to where br.close() is.

Now, when you have done that, your code is almost working. The only thing is - you now get a NullPointerException. This is because you don't change your line after all entries are read. The easy fix to this is change from

while(line.equals("Start")) { ...

to

if(line.equals("Start")) { ...

Also, there are some other not-so-neat things in your code, but I will leave it for now - experience comes with time.

ZetQ
  • 51
  • 4
0

For Java 8:

List<String> stopWords = Arrays.asList("Start", "End");
try (BufferedReader reader = new BufferedReader(input))) {
   List<String> lines = reader.lines()
     .map(String::trim)
     .filter(s -> !StringUtils.isEmpty(s) && !stopWords.contains(s))
     .collect(Collectors.toList());
}
vk23
  • 468
  • 7
  • 16