【发布时间】:2010-01-11 16:10:33
【问题描述】:
我已经很多年没有写过任何 Java 了,我回过头来用一个简单的“从文件读取”示例来刷新我的记忆。这是我的代码..
import java.io.*;
public class filereading {
public static void main(String[] args) {
File file = new File("C:\\file.txt");
FileInputStream fs = null;
BufferedInputStream bs = null;
DataInputStream ds = null;
try
{
fs = new FileInputStream(file);
bs = new BufferedInputStream(bs);
ds = new DataInputStream(ds);
while(ds.available()!= 0)
{
String readLine = ds.readLine();
System.out.println(readLine);
}
ds.close();
bs.close();
fs.close();
}
catch(FileNotFoundException e)
{
e.printStackTrace();
}
catch(IOException e)
{
e.printStackTrace();
}
}
}
这编译得很好(虽然显然 ds.readLine() 已被弃用),但在运行时,这给了我
线程“main”中的异常 java.lang.NullPointerException 在 java.io.FilterInputStream.available(未知 来源)在 filereading.main(filereading.java:21)
什么给了?
【问题讨论】:
-
另外请注意
.available()可能不知道你认为它做了什么。 -
不在问题中,但您应该在 finally 块中关闭资源 (
FileInputStream)。为了帮助这个从try块中提取分配(并使变量final)。 -
@Tom Hawtin。 +1。并且只在派生最多的资源句柄上执行一次,在本例中为
DataInputStream ds。