Method 1
ByteBuffer byteBuffer = reqData.getByteBuffer();
File localFile = new File(ROOTPATH, localFileName);
FileUtils.copyInputStreamToFile(new ByteArrayInputStream(byteBuffer.array()), localFile);
The file generated is different from the origin one in Method 1.
Method 2
ByteBuffer byteBuffer = reqData.getByteBuffer();
byte[] arr = new byte[byteBuffer.remaining()];
...
The file generated is the same as the origin one in Method 2.
Why the bytes got by ByteBuffer.array() is wrong? Is it because of ByteBuffer.array() itself, or ByteArrayInputStream constructor?
Ah, the mysterious case of the mischievous bytes! Well, my friend, let's unravel this puzzle !
In Method 1, you used ByteBuffer's
array()method to get the byte array and then converted it into a file usingByteArrayInputStream. But alas! The resulting file turned out different from the original.Now, let's dive into the possible culprits. Could it be ByteBuffer.array() playing tricks on you? Is it secretly swapping bytes like a mischievous imp? Or perhaps, it's the ByteArrayInputStream constructor pulling a prank of its own?
Well, fear not, dear user! The answer lies in how ByteBuffer works. You see, the byte array obtained from
array()includes the entire internal buffer, not just the portion you've actually written to. It's like taking a snapshot of the whole aquarium, even if you only have a goldfish swimming around.So when you pass that byte array to
ByteArrayInputStreamand create a new file, you inadvertently include all those extra, unwritten bytes. And voila! You end up with a different file compared to the original. Sneaky, right?But don't lose hope! Method 2 comes to the rescue. By using
byteBuffer.remaining()and creating a new byte array with just the necessary length, you avoid capturing those pesky unmodified bytes. Thus, the file generated is identical to the original. Hooray for Method 2!So the bytes aren't playing games; it's just a quirk of the
array()method and its sneaky surprises. Keep Method 2 in your pocket, and your files shall remain unaltered. Happy coding my friend, and may your bytes always be well-behaved!