I am trying to use some of the code that I found at the bottom of this page . Here is the code in the 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 goal is to count the lines of a text file, save that number as an integer, and then use that integer in my main class. In my main class, I tried several different ways to make this happen, but (as a new programmer) I'm 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 "unregistered java.io.IOException exception; it should be detected or declared that it will be thrown." I do not understand why I get this because, as I see it, an exception is declared in my countLines method. I tried using the catch try block right below this last bit of code that I posted, but that didn't work either (I don't think I did it right, though). Here is my attempt to catch the 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!
java try-catch ioexception
ubiquibacon
source share