簡體   English   中英

從二進制文件Java錯誤讀取int

[英]Incorrectly reading int from binary file Java

我正在嘗試從二進制.dat文件中讀取日期(6個整數的集合)和溫度(雙精度)。

經過多次嘗試,我終於到達文件正在工作的階段,但是它以我無法識別的格式返回int。 例如。 日期2017-03-02 11:33,溫度3.8讀取為:

測量:515840-1024-1024 2816 8512 241591910溫度:1.9034657819129845E185

有什么想法,如何更改代碼?

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) {

問題在這里。 這會在每次迭代時讀取並丟棄文件的一個字節,因此所有后續讀取都不同步。

使用DataInputStreamObjectInputStream進行循環的正確方法是使用while (true)循環,並在read()返回-1, readLine()返回null或對於所有其他X拋出readXXX()時終止它,這將引發EOFException.

請注意,您通常不需要在EOFException上記錄或打印堆棧跟蹤,因為這是正常的循環終止條件…… 除非您有理由期望更多的數據,例如,文件以您沒有的記錄計數開始尚未到達,這可能表明該文件已被截斷,因此已損壞。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM