views:

397

answers:

3

Hi all,

I am trying to use a bit of code I found at the bottom of this page. Here is the code in a class that I created for it:

import java.io.LineNumberReader;
import java.io.FileReader;
import java.io.IOException;

public class LineCounter {
  public static int countLines(String filename) throws IOException {
    LineNumberReader reader  = new LineNumberReader(new FileReader(filename));
    int cnt = 0;
    String lineRead = "";
    while ((lineRead = reader.readLine()) != null) {}
    cnt = reader.getLineNumber();
    reader.close();
    return cnt;
  }
}

My objective is to count the lines of a text file, store that number as an integer, then use that integer in my main class. In my main class I tried a few different ways of making this happen, but (being a new programmer) I am missing something. Here is the first thing I tried:

String sFileName = "MyTextFile.txt";
private int lineCount = LineCounter.countLines(sFileName);

With this attempt I get the error "unreported exception java.io.IOException; must be caught or declared to be thrown." I don't understand why I am getting this because as I can see the exception is declared in my "countLines" method. I tried to use a try catch block right under that last bit of code I posted, but that didn't work either (I don't think I did it right though). Here is my try catch attempt:

String sFileName = "MyTextFile.txt";
private int lineCount;{
    try{
        LineCounter.countLines(sFileName);
    }
    catch(IOException ex){
        System.out.println (ex.toString());
        System.out.println("Could not find file " + sFileName);
    }
}

Please show me the way! Thanks in advance for your help!

A: 

Your countLines(String filename) method throws IOException.

You can't use it in a member declaration. You'll need to perform the operation in a main(String[] args) method.

Your main(String[] args) method will get the IOException thrown to it by countLines and it will need to handle or declare it.

Try this to just throw the IOException from main

public class MyClass {
  private int lineCount;
  public static void main(String[] args) throws IOException {
    lineCount = LineCounter.countLines(sFileName);
  }
}

or this to handle it and wrap it in an unchecked IllegalArgumentException:

public class MyClass {
  private int lineCount;
  private String sFileName  = "myfile";
  public static void main(String[] args) throws IOException {
    try {
      lineCount = LineCounter.countLines(sFileName);
     } catch (IOException e) {
       throw new IllegalArgumentException("Unable to load " + sFileName, e);
     }
  }
}
Brabster
Sorry, misread the question at first!
Brabster
Thanks for your reply, you all are awesome!
typoknig
+1  A: 

Initializer block is just like any bits of code; it's not "attached" to any field/method preceding it. To assign values to fields, you have to explicitly use the field as the lhs of an assignment statement.

private int lineCount; {
    try{
        lineCount = LineCounter.countLines(sFileName);
        /*^^^^^^^*/
    }
    catch(IOException ex){
        System.out.println (ex.toString());
        System.out.println("Could not find file " + sFileName);
    }
}

Also, your countLines can be made simpler:

  public static int countLines(String filename) throws IOException {
    LineNumberReader reader  = new LineNumberReader(new FileReader(filename));
    while (reader.readLine() != null) {}
    reader.close();
    return reader.getLineNumber();
  }

Based on my test, it looks like you can getLineNumber() after close().

polygenelubricants
The answer is technically correct (the OP simply forgot to assign the value to the reference), but that was not a **static** initializer block. It's just an initializer block :)
BalusC
Your first bit of code works perfect! I was so close :) Your second bit of code works too, but NetBeans tells me the while loop is empty. The program still compiles and runs ok, so I guess that is acceptable?
typoknig
It's simply ignoring the content. You're actually only interested in the amount of lines. You can alternatively also use `BufferedReader` in combination with `int count` which you increment inside the loop.
BalusC
I changed the `countLines` again to be more similar to what you had before.
polygenelubricants
@BalusC yes, you're right about the non-static part. Fixed.
polygenelubricants
A: 

The reason you are getting the the IOException is because you are not catching the IOException of your countLines method. You'll want to do something like this:

public static void main(String[] args) {
  int lines = 0;  

  // TODO - Need to get the filename to populate sFileName.  Could
  // come from the command line arguments.

   try {
       lines = LineCounter.countLines(sFileName);
    }
    catch(IOException ex){
        System.out.println (ex.toString());
        System.out.println("Could not find file " + sFileName);
    }

   if(lines > 0) {
     // Do rest of program.
   }
}
JasCav
Thanks for the reply!
typoknig