2015-02-11 115 views
-1

我試圖從二進制.dat文件讀取日期(6整數的集合)和溫度(雙精度)。從二進制文件讀取int不正確Java

多次嘗試後,我終於得到了該文件的工作階段,但它在我無法識別的格式返回int。例如。日期2017年3月2日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 

回答

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

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

正確的方法循環使用DataInputStreamObjectInputStream是一個while (true)環和終止它的時候read()返回-1,readLine()回報null,或readXXX()任何其他X拋出你不EOFException.

注t通常需要在EOFException上記錄或打印堆棧跟蹤,因爲它是正常的循環終止條件... 除非您有理由期待更多的數據,例如您的文件以您尚未達到的記錄計數開始,這可能表示文件被截斷並因此損壞。

+0

很好,非常感謝 – Turo 2015-02-12 00:19:53