Note that there are some explanatory texts on larger screens.

plurals
  1. POJava Try and Catch IOException Problem
    primarykey
    data
    text
    <p>I am trying to use a bit of code I found at the bottom of <a href="https://stackoverflow.com/questions/453018/number-of-lines-in-a-file-in-java">this page</a>. Here is the code in a class that I created for it:</p> <pre><code>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; } } </code></pre> <p><strong>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.</strong> 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:</p> <pre><code>String sFileName = "MyTextFile.txt"; private int lineCount = LineCounter.countLines(sFileName); </code></pre> <p>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:</p> <pre><code>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); } } </code></pre> <p>Please show me the way! Thanks in advance for your help!</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload