Java尝试和捕获IOException问题
发布时间:2020-05-25 00:09:51 所属栏目:Java 来源:互联网
导读:我试图使用我在 this page底部找到的一些代码.这是我为它创建的类中的代码: import java.io.LineNumberReader;import java.io.FileReader;import java.io.IOException;public class LineCounter { public static int countLines(String file
|
我试图使用我在 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(). (编辑:安卓应用网) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
