2012-06-13 25 views
4

由於外部C++應用程序必須讀取此文件,因此我必須在文件中寫入4bytes,代表little endian中的整數(java use big endian)。我的代碼不會在te文件中寫入任何內容,但de buffer中有數據。爲什麼? 我funcion:在小端中編寫一個整數

public static void copy(String fileOutName, boolean append){ 
    File fileOut = new File (fileOutName); 

    try { 
     FileChannel wChannel = new FileOutputStream(fileOut, append).getChannel(); 

     int i = 5; 
     ByteBuffer bb = ByteBuffer.allocate(4); 
     bb.order(ByteOrder.LITTLE_ENDIAN); 
     bb.putInt(i); 

     bb.flip(); 

     int written = wChannel.write(bb); 
     System.out.println(written);  

     wChannel.close(); 
    } catch (IOException e) { 
    } 
} 

我的電話:

copy("prueba.bin", false); 
+8

不要忽略異常。在'catch'塊中寫入'e.printStackTrace()' – alaster

+0

我試過這段代碼,它在文件中寫了4個字節 – Evans

+1

這可能是非同步IO的問題。寫入方法不會阻止,因此無法保證在您關閉時它會完成。並且關閉力量阻止了線程立即退出,這可能會導致異常中止寫入操作,而您忽略了該異常。 – jpm

回答

6

當你不知道爲什麼有些東西失敗了,這是一個壞主意,忽略一個空try-catch塊的異常。

在一個無法創建文件的環境中運行程序的可能性非常好;然而,你處理這種特殊情況的指示是什麼都不做。所以,很可能你有一個試圖運行的程序,但由於某種原因失敗了,甚至沒有向你顯示原因。

試試這個

public static void copy(String fileOutName, boolean append){ 
    File fileOut = new File (fileOutName); 

    try { 
     FileChannel wChannel = new FileOutputStream(fileOut, append).getChannel(); 

     int i = 5; 
     ByteBuffer bb = ByteBuffer.allocate(4); 
     bb.order(ByteOrder.LITTLE_ENDIAN); 
     bb.putInt(i); 

     bb.flip(); 

     int written = wChannel.write(bb); 
     System.out.println(written);  

     wChannel.close(); 
    } catch (IOException e) { 
// this is the new line of code 
     e.printStackTrace(); 
    } 
} 

而且我敢打賭,你發現它爲什麼不馬上工作。

+0

我會使用e.printStackTrace()而不是println,以便您可以獲得更多的上下文。 – templatetypedef

+0

@templatetypedef當然,我會更新帖子。 –

+0

謝謝,我忘了這個。 只有二進制中的整數5是空白字符並且如果我將'i'變量的值更改爲54564645,%ó@的結果是沒有任何問題:p – abogarill

相關問題