我想使用我在这个页面底部找到的一些代码。以下是我为此创建的类中的代码:
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块,但也没有起作用(虽然我认为我做错了)。以下是我的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);
}
}
请告诉我具体方法!
BufferedReader
与int count
结合使用,然后递增计数。 - BalusCcountLines
,使其更类似于您之前的代码。 - polygenelubricants