Reputation: 16117
I am reading a file in Java using this code
import java.io.*;
public class IOReadDataStreams {
public static void main(String[] args)throws IOException{
DataInputStream in = null;
try{
in = new DataInputStream(
new BufferedInputStream(new FileInputStream("invoicedata")));
int unit;
double price;
String desc;
while(true){
unit = in.readInt();
price = in.readDouble();
desc = in.readUTF();
System.out.println(unit+" " + price +" "+ desc);
}
}catch(EOFException e){
e.printStackTrace();
}
finally{
if(in != null)
in.close();
}
}
}
The file that I was trying to read was made by this Piece of code
import java.io.IOException;
import java.io.DataOutputStream;
import java.io.FileOutputStream;
import java.io.BufferedOutputStream;
import java.io.DataInputStream;
public class IODataStreams {
static final String dataFile = "invoicedata";
static final double[] prices = new double[]{19.99, 9.99,15.99,3.99,4.99};
static final int[] unitCount = new int[]{12,8,13,29,50};
static final String[] desc = new String[]{
"Java T Shirt",
"C# T Shirt",
"PHP T Shirt",
"Ruby T Shirt",
"Go! T Shirt"
};
public static void main(String[] args) throws IOException{
DataOutputStream out = null;
DataInputStream in = null;
try{
out = new DataOutputStream(new BufferedOutputStream(new FileOutputStream("invoicedata")));
for(int i = 0 ; i < prices.length; i++){
out.writeUTF(desc[i]);
out.writeInt(unitCount[i]);
out.writeDouble(prices[i]);
}
}finally{
if(out != null)
out.close();
}
}
}
Now I am wondering why my first code (the one that reads the file) is not Printing the price,desc and the unit. it keeps on returning a EOFException
The error is specifically on this line
desc = in.readUTF();
Upvotes: 0
Views: 2226
Reputation: 143866
You are writing data in this order:
out.writeUTF(desc[i]);
out.writeInt(unitCount[i]);
out.writeDouble(prices[i]);
But reading data in the wrong order:
unit = in.readInt();
price = in.readDouble();
desc = in.readUTF();
You need to read and write the data in the same order, specifically the UTF
bit, because that doesn't translate into a number.
When I switched these lines so that the read and write was in the same order, this is what IOReadDataStreams
outputed:
12 19.99 Java T Shirt
8 9.99 C# T Shirt
13 15.99 PHP T Shirt
29 3.99 Ruby T Shirt
50 4.99 Go! T Shirt
Before reaching the EOF of the file and throwing (like it should) an EOFException.
Upvotes: 2