ubi*_*con 9 java try-catch ioexception
我试图使用我在本页底部找到的一些代码.这是我为它创建的类中的代码:
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;
}
}
Run Code Online (Sandbox Code Playgroud)
我的目标是计算文本文件的行,将该数字存储为整数,然后在我的主类中使用该整数. 在我的主要课程中,我尝试了几种不同的方法来实现这一点,但是(作为一名新程序员)我错过了一些东西.这是我尝试的第一件事:
String sFileName = "MyTextFile.txt";
private int lineCount = LineCounter.countLines(sFileName);
Run Code Online (Sandbox Code Playgroud)
通过此尝试,我得到错误"未报告的异常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);
}
}
Run Code Online (Sandbox Code Playgroud)
请告诉我方式!在此先感谢您的帮助!
初始化程序块就像任何代码位一样。它没有“附加”到它前面的任何字段/方法。要将值分配给字段,您必须显式使用字段作为赋值语句的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);
}
}
Run Code Online (Sandbox Code Playgroud)
另外,您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();
}
Run Code Online (Sandbox Code Playgroud)
根据我的测试,它看起来像你可以getLineNumber()以后close()。
| 归档时间: |
|
| 查看次数: |
151267 次 |
| 最近记录: |