用小端写一个整数

abo*_*ill 4 java io nio bytebuffer endianness

我必须写一个文件4bytes表示一个小端的整数(java使用大端),因为外部c ++应用程序必须读取此文件.我的代码不在te文件中写任何东西,但de buffer里面有数据.为什么?我的功能:

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) {
     }
}
Run Code Online (Sandbox Code Playgroud)

我的电话:

copy("prueba.bin", false);
Run Code Online (Sandbox Code Playgroud)

Edw*_*uck 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();
     }
}
Run Code Online (Sandbox Code Playgroud)

而且我打赌你会发现为什么它不会立即起作用.