Reading and writing a binary file in Java (if half of the damaged file)

I have some working code in python that I need to convert to Java.

I read quite a few topics on this forum, but could not find the answer. I am reading a JPG image and converting it to an array of bytes. Then I write this buffer to another file. When I compare the recorded files with both Java and python code, the bytes at the end do not match. Please let me know if you have any suggestion. I need to use an array of bytes to pack the image into a message that needs to be sent to a remote server.

Java code (running on Android)

Reading file:

File queryImg = new File(ImagePath);
int imageLen = (int)queryImg.length();
byte [] imgData = new byte[imageLen];
FileInputStream fis = new FileInputStream(queryImg);
fis.read(imgData);

File record:

FileOutputStream f = new FileOutputStream(new File("/sdcard/output.raw"));
f.write(imgData);
f.flush();
f.close();

Thank!

+5
source share
2

InputStream.read - , . , , :

public void pump(InputStream in, OutputStream out, int size) {
    byte[] buffer = new byte[4096]; // Or whatever constant you feel like using
    int done = 0;
    while (done < size) {
        int read = in.read(buffer);
        if (read == -1) {
            throw new IOException("Something went horribly wrong");
        }
        out.write(buffer, 0, read);
        done += read;
    }
    // Maybe put cleanup code in here if you like, e.g. in.close, out.flush, out.close
}

, Apache Commons IO , .

+5

, int , , .

0

All Articles