【问题标题】:Write an integer in little endian用小端写一个整数
【发布时间】:2012-06-16 16:05:31
【问题描述】:

我必须在一个 4bytes 的文件中写入一个小端(java 使用大端)表示整数的文件,因为外部 c++ 应用程序必须读取这个文件。我的代码没有在 te 文件中写入任何内容,但 de 缓冲区中有数据。为什么? 我的功能:

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

【问题讨论】:

  • 不要忽略异常。在catch块中写入e.printStackTrace()
  • 我试过那个代码,它在文件中写入了 4 个字节
  • 这可能是非同步 IO 的问题。 write 方法不会阻塞,因此无法保证它会在您调用 close 时完成。并且 close 强制阻塞的线程立即退出,这可能会中止写入并出现您忽略的异常。

标签: java io nio bytebuffer endianness


【解决方案1】:

当您不知道某事失败的原因时,在空的 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();
     }
}

我敢打赌,你会发现为什么它不能马上工作。

【讨论】:

  • 我会使用 e.printStackTrace() 而不是 println,这样您可以获得更多上下文。
  • 谢谢,我忘记了。没有任何问题,只是二进制中的整数 5 是一个空白字符,如果我将 'i' 变量的值更改为 54564645,则 %ó@ 是结果:p
猜你喜欢
  • 2020-11-13
  • 1970-01-01
  • 1970-01-01
  • 2021-02-20
  • 2021-04-25
  • 2017-01-23
  • 2017-05-08
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多