简体   繁体   English

从二进制文件Java错误读取int

[英]Incorrectly reading int from binary file Java

I'm trying to read a date (set of 6 integers) and temperature (double) from binary .dat file. 我正在尝试从二进制.dat文件中读取日期(6个整数的集合)和温度(双精度)。

After multiple tries I finally got to the stage where the file is working, but it's returning int in the format I cannot recognize. 经过多次尝试,我终于到达文件正在工作的阶段,但是它以我无法识别的格式返回int。 Eg. 例如。 date 2017-03-02 11:33 , and temperature 3.8 is read as: 日期2017-03-02 11:33,温度3.8读取为:

Measure : 515840-1024-1024 2816 8512 241591910 temperature: 1.9034657819129845E185 测量:515840-1024-1024 2816 8512 241591910温度:1.9034657819129845E185

Any ideas, how to change the code? 有什么想法,如何更改代码?

public void readFile() {

                try {
                    DataInputStream dis = null;
                    BufferedInputStream bis = null;
                    try {
                        FileInputStream fis = new FileInputStream(fileLocation);

                        int b;
                        bis = new BufferedInputStream(fis);
                        dis = new DataInputStream(fis);

                        while ((b = dis.read()) != -1) {

    System.out.println("Measure : " + dis.readInt() + "-" 
    + dis.readInt() + "-" + dis.readInt() + " " + 
    dis.readInt() + " " + dis.readInt() + " "
    + dis.readInt() + " Temperature: "+ dis.readDouble());

                        }
                    } finally {
                        dis.close();
                    }
                } catch (FileNotFoundException ex) {
                    ex.printStackTrace();
                } catch (EOFException f) {
                    f.printStackTrace(); 
                } catch (IOException e) {
                    e.printStackTrace();
                }

            } // readFile   
while ((b = dis.read()) != -1) {

The problem is here. 问题在这里。 This reads and discards a byte of the file on every iteration, so all subsequent reads are out of sync. 这会在每次迭代时读取并丢弃文件的一个字节,因此所有后续读取都不同步。

The correct way to loop with a DataInputStream or ObjectInputStream is with a while (true) loop, and terminating it when read() returns -1, readLine() returns null , or readXXX() for any other X throws EOFException. 使用DataInputStreamObjectInputStream进行循环的正确方法是使用while (true)循环,并在read()返回-1, readLine()返回null或对于所有其他X抛出readXXX()时终止它,这将引发EOFException.

Note that you don't normally need to log or print a stack trace on EOFException , as it's a normal loop termination condition ... unless you had reason to expect more data, eg your file started with a record count that you haven't reached yet, which might indicate that the file was truncated and therefore corrupt. 请注意,您通常不需要在EOFException上记录或打印堆栈跟踪,因为这是正常的循环终止条件…… 除非您有理由期望更多的数据,例如,文件以您没有的记录计数开始尚未到达,这可能表明该文件已被截断,因此已损坏。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM