I am trying to read a csv file and having the output shown in the console. 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.
Edit: it's a CSV file, so of course it's text!
You'll probably want to use a CSV parser as well as a BufferedReader or Scanner.