Link to home
Start Free TrialLog in
Avatar of mkisiu
mkisiuFlag for Poland

asked on

Java copying blocks of bytes from the file

Hello,
I would like to ask for help.
I'm trying to perform the partial copying of the file in Java (as binary, using FileInputStream and FileOutputStream). By partial I mean I want to copy whole file but in blocks of 55516 bytes (as preparation for the next features in the application).
Pls find the code below:
 
Each block of bytes starts with 00000 (5 zeros). The problem is that after the copy has been made as the FileOut, the each block of bytes in the target file starts with 0000 (4 zeros) instead of 00000 (5 zeros).

Cld you pls help me to find my mistake?
Kind regards
ASKER CERTIFIED SOLUTION
Avatar of Holger101497
Holger101497

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Holger101497
Holger101497

P.S.: Oh yeah, one more thing: As I mentioned, read(byteBlock) (parameters 0 and length are not necessary!) reads UP TO x bytes, but can read less even if more bytes are available. I have never encountered this behavior with "plain files", but it does happen with any other kind of stream, including ZipStreams (from files) and of course network streams.
You *should* therefore extend your program to make sure you've actually read 55516 bytes before you continue processing. Even if it works fine now, this behavior is not specified and might "break" in a new or different version of the Java virtual machine or on a different platform (Linux, MacOS, ...)

Good luck!
Avatar of Mick Barry
following should help you understand how to copy between streams

http://helpdesk.objects.com.au/java/how-do-i-copy-one-stream-to-another-using-java

also be aware that the read function does not guarantee to fill the buffer (it returns the number of bytes read)
oh, and another observation ... (I just post too quickly... but it has happened that I wrote a long answer and somebody else posted a very short answer while I wrote mine...):
Are you sure "each block of bytes in the target file starts with 0000"? I would expect the first one to start with 0000x, the second one to start with 000xy, the third one to start with 00xyz and the fifth (and later) blocks to start with random data, because your current code reads 55517 in each loop and the remaining bytes in the last one... (with one byte of wrong data at the end for each block that was read)
Avatar of mkisiu

ASKER

Thanks a lot. The solution works perfectly :)