2012-06-13 76 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

相关问题