nonexistential
nonexistential

Reputation: 67

Issues on File Splitting Using Java

A file when split to different byte arrays using java, when joined back doesn't get rendered by the file's application. This happens even when the number of bytes are same on both the original file and rejoined file.

The objective here is to split a large file into different byte arrays and rejoin these byte arrays using a different programming language (C#) over the network.

The code that I have written for splitting is as follows:

File f = new File(fileLoc);
FileInputStream fi = new FileInputStream(f);
int size = fi.available();

int MB2 = 1048576 * 2;
int total = size / MB2;
if (size % MB2 != 0) {
    total += 1;
}
int ch;

while (size > 0) {
    int arraysize;
    if (size < MB2) {
        arraysize = size;
    } else
        arraysize = MB2;
    byte bytes_read[] = new byte[arraysize];
    ch = fi.read(bytes_read, 0, arraysize);
    // The byte_read is added to an array list of byte[]
    // and send along with certain other parameters 
    size = size - ch;
    count++;
}
fi.close();

Upvotes: 0

Views: 97

Answers (1)

JB Nizet
JB Nizet

Reputation: 691635

You have two problems:

  • you're using available() as a way to know a file length. that's not what the method does. available() should almost never be used. I've never seen any use-case where using it was a good idea.
  • you're using the read() method and disregard its returned value. You use it to dcrment the size variable, but you don't care if you byte array is filled with read bytes or filled with zeroes. read() isn't guaranteed to read as many bytes as you asked.

There could be other errors in the way bytes are sent over the wire and read by the other side as well.

Upvotes: 2

Related Questions