当前位置: 动力学知识库 > 问答 > 编程问答 >

android - Reading and writing binary file in Java (seeing half of the file being corrupted)

问题描述:

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

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

Java code (Running on Android)

Reading the file:

File queryImg = new File(ImagePath);

int imageLen = (int)queryImg.length();

byte [] imgData = new byte[imageLen];

FileInputStream fis = new FileInputStream(queryImg);

fis.read(imgData);

Writing the file:

FileOutputStream f = new FileOutputStream(new File("/sdcard/output.raw"));

f.write(imgData);

f.flush();

f.close();

Thanks!

网友答案:

InputStream.read is not guaranteed to read any particular number of bytes and may read less than you asked it to. It returns the actual number read so you can have a loop that keeps track of progress:

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
}

I believe Apache Commons IO has classes for doing this kind of stuff so you don't need to write it yourself.

网友答案:

Your file length might be more than int can hold and than you end up having wrong array length, hence not reading entire file into the buffer.

分享给朋友:
您可能感兴趣的文章:
随机阅读: