gpt4 book ai didi

Java - 从文件读取输入。 java.io.FilterInputStream.available(来源未知)?

转载 作者:行者123 更新时间:2023-12-01 06:59:44 24 4
gpt4 key购买 nike

我已经很多年没有写过任何 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() 已被弃用),但在运行时,这给了我

Exception in thread "main" java.lang.NullPointerException at java.io.FilterInputStream.available(Unknown Source) at filereading.main(filereading.java:21)

什么给出了?

最佳答案

您犯了一个简单的拼写错误:

ds = new DataInputStream(ds);

应该是

ds = new DataInputStream(bs);

您的代码正在使用 null 源初始化 DataInputStream,因为 ds 尚未创建。

话虽如此,Jon Skeet 的答案提供了一种更好的方法来编写文件读取程序(并且您应该始终使用 Readers/Writers 而不是 Streams 处理文本时)。

关于Java - 从文件读取输入。 java.io.FilterInputStream.available(来源未知)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2043028/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com