用Java读写二进制文件(看到一半文件被损坏)

2024-02-28

我有一些 python 工作代码,需要将其转换为 Java。

我在这个论坛上阅读了很多帖子,但找不到答案。我正在读取 JPG 图像并将其转换为字节数组。然后我将此缓冲区写入另一个文件。当我比较 Java 和 Python 代码写入的文件时,末尾的字节不匹配。如果您有建议,请告诉我。我需要使用字节数组将图像打包到需要发送到远程服务器的消息中。

Java代码(在Android上运行)

读取文件:

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

写入文件:

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

Thanks!


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 有用于执行此类操作的类,因此您无需自己编写。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

用Java读写二进制文件(看到一半文件被损坏) 的相关文章

随机推荐