读取文件时出现Java EOFException

时间:2012-08-10 03:26:36

标签: java io stream datainputstream

我正在使用此代码

在Java中读取文件
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();
        }
    }
}

我试图阅读的文件是由这段代码制作的

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();
        }

    }

}

现在我想知道为什么我的第一个代码(读取文件的代码)不是打印价格,desc和单位。它继续返回EOFException

错误具体在这一行

desc = in.readUTF();

1 个答案:

答案 0 :(得分:2)

您按此顺序编写数据:

            out.writeUTF(desc[i]);
            out.writeInt(unitCount[i]);
            out.writeDouble(prices[i]);

但是以错误的顺序读取数据:

            unit = in.readInt();
            price = in.readDouble();
            desc = in.readUTF();

您需要以相同的顺序读取和写入数据,特别是UTF位,因为这不会转换为数字。

当我切换这些行以使读写顺序相同时,这就是IOReadDataStreams输出的内容:

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

在到达文件的EOF并抛出(就像它应该)EOFException之前。