我正在尝试使用我在底部找到的一些代码这一页 https://stackoverflow.com/questions/453018/number-of-lines-in-a-file-in-java。这是我为其创建的类中的代码:
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);
}
}
请给我指路!
初始化块就像任何代码位一样;它没有“附加”到它前面的任何字段/方法。要将值分配给字段,您必须显式使用该字段作为赋值语句的左侧。
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();
}
根据我的测试,看起来你可以getLineNumber()
after close()
.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)