微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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().

原文地址:https://www.jb51.cc/java/128481.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐