用Java读取和写入二进制文件(看到文件的一半被破坏)
我在python中有一些工作代码,我需要转换为Java。
我在这个论坛上读过很多post但是找不到答案。 我正在读取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();
谢谢!
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, eg in.close, out.flush, out.close }
我相信Apache Commons IO有用于完成这类工作的类,所以你不需要自己编写它。
您的文件长度可能超过int可以容纳的数量,并且最终导致数组长度错误,因此不会将整个文件读入缓冲区。