[英]Why am I getting an EOFException in my Java code?
I am trying to read a csv file and having the output shown in the console. 我正在尝试读取一个csv文件,并在控制台中显示输出。 However, I can't understand why I am getting an end of file exception and nothing is being shown in the console?
但是,我不明白为什么我要结束文件异常并且控制台中什么也没有显示?
The Exception message is: 异常消息是:
java.io.EOFException
at java.io.DataInputStream.readFully(DataInputStream.java:197)
at java.io.DataInputStream.readUTF(DataInputStream.java:609)
at java.io.DataInputStream.readUTF(DataInputStream.java:564)
at ByteIO.main(ByteIO.java:17)
My code is: 我的代码是:
import java.io.*;
import javax.swing.*;
public class ByteIO
{
public static void main(String[] args)
{
try
{
FileInputStream fis = new FileInputStream("BaseballNames1.csv");
BufferedInputStream bis = new BufferedInputStream(fis);
DataInputStream dis = new DataInputStream(bis);
while(dis.available() > 0)
{
String header = (dis.readUTF());
String firstName = (dis.readUTF());
String lastName = (dis.readUTF());
String fullName = (firstName + " " + lastName);
int birthDay = (dis.readInt());
int birthMonth = (dis.readInt());
int birthYear = (dis.readInt());
String birthDate = (birthMonth + "/" + birthDay + "/" + birthYear);
int weight = (dis.readInt());
double height = (dis.readDouble());
System.out.println( header + fullName + birthDate + weight + height);
dis.close();
}
}
catch(EOFException eof)
{
System.out.println("End of File!");
}
catch(FileNotFoundException fe)
{
System.out.println("File not found!");
}
catch(IOException ie)
{
ie.printStackTrace();
}
}
}
I'm guessing that your file is not a binary data file, but rather is filled with text. 我猜您的文件不是二进制数据文件,而是充满了文本。 If so, use a Scanner or a Reader such as a FileReader wrapped in a BufferedReader, not a DataInputStream.
如果是这样,请使用包裹在BufferedReader中的Scanner或Reader(例如FileReader),而不是DataInputStream。
Edit: it's a CSV file, so of course it's text! 编辑:这是CSV文件,所以当然是文本!
You'll probably want to use a CSV parser as well as a BufferedReader or Scanner. 您可能需要使用CSV解析器以及BufferedReader或Scanner。
You didn't write the file with writeUTF(),
so readUTF()
can't read it. 您没有使用
writeUTF(),
写入文件writeUTF(),
因此readUTF()
无法读取它。 See the Javadoc. 请参阅Javadoc。 A CSV file is text, not what results from
writeUTF().
CSV文件是文本,而不是
writeUTF().
产生的结果writeUTF().
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.