u3l*_*u3l 1 java file path bufferedreader
我正在尝试逐行读取文件,但每次运行程序时,我都会在行中得到一个NullPointerException,spaceIndex = line.indexOf(" ");这显然意味着该行为null.然而.我知道我正在使用的文件正好有7行(即使我打印了值numLines,我得到了值7.然而当我尝试读取一行到我的字符串时,我仍然得到一个nullpointerexception.
// File file = some File I take in after clicking a JButton
Charset charset = Charset.forName("US-ASCII");
try (BufferedReader reader = Files.newBufferedReader(file.toPath(), charset)) {
String line = "";
int spaceIndex;
int numLines = 0;
while(reader.readLine()!=null) numLines++;
for(int i = 0; i<numLines; i++) {
line = reader.readLine();
spaceIndex = line.indexOf(" ");
System.out.println(spaceIndex);
}
Run Code Online (Sandbox Code Playgroud)
PS :(我实际上并没有使用这段代码来打印空间的索引,我替换了循环中的代码,因为它有很多,而且会让它读起来更长)
如果我要以错误的方式阅读这些行,那么如果有人可以提出另一种方式会很好,因为到目前为止,我尝试过的每一种方式都给了我同样的例外.谢谢.
当你开始for循环时,阅读器已经在文件的末尾(来自while循环).
因此,readLine()将永远回归null.
当你第一次读取文件时,你应该摆脱for循环并在循环中完成所有工作while.
| 归档时间: |
|
| 查看次数: |
6742 次 |
| 最近记录: |