Write an integer at the small end

I need to write to a 4bytes file representing an integer in little endian (java use big endian), because an external C ++ application needs to read this file. My code does not write anything in the te file, but there is data inside the buffer. What for? my function:

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) { } } 

my call:

 copy("prueba.bin", false); 
+4
source share
1 answer

If you don't know why something didn't work out, it's a bad idea to ignore exceptions in an empty try-catch block.

The odds are excellent that you run the program in an environment where the file cannot be created; however, the instructions you gave to deal with such an exceptional situation do nothing. So, the likelihood that you have a program that tried to run, but for some reason failed, and this was due to the fact that you did not even indicate the reason.

try it

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

And I bet you will find out why this doesn't work right away.

+6
source

All Articles