Java尝试和捕获IOException问题

我试图使用我在 this page底部找到的一些代码.这是我为它创建的类中的代码
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;
  }
}

我的目标是计算文本文件的行,将该数字存储为整数,然后在我的主类中使用该整数.在我的主要课程中,我尝试了几种不同的方法来实现这一点,但(作为一名新程序员)我错过了一些东西.这是我尝试的第一件事:

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

通过此尝试,我收到错误“未报告的异常java.io.IOException;必须被捕获或声明被抛出”.我不明白为什么我得到这个,因为我可以看到异常是在我的“countLines方法中声明的.我尝试在我发布的最后一段代码下使用try catch块,但这也没有用(我不认为我做得对).这是我试试的尝试:

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);
    }
}

请告诉我方式!在此先感谢您的帮助!

解决方法

初始化器块就像任何代码位一样;它不会“附加”到它之前的任何字段/方法.要为字段赋值,必须显式使用该字段作为赋值语句的lhs.
private int lineCount; {
    try{
        lineCount = LineCounter.countLines(sFileName);
        /*^^^^^^^*/
    }
    catch(IOException ex){
        System.out.println (ex.toString());
        System.out.println("Could not find file " + sFileName);
    }
}

此外,您的countLines可以更简单:

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

根据我的测试,看起来你可以在close()之后获取LineNumber().

相关文章

最近看了一下学习资料,感觉进制转换其实还是挺有意思的,尤...
/*HashSet 基本操作 * --set:元素是无序的,存入和取出顺序不...
/*list 基本操作 * * List a=new List(); * 增 * a.add(inde...
/* * 内部类 * */ 1 class OutClass{ 2 //定义外部类的成员变...
集合的操作Iterator、Collection、Set和HashSet关系Iterator...
接口中常量的修饰关键字:public,static,final(常量)函数...