smi*_*ten 6 java binary android file
我在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);
Run Code Online (Sandbox Code Playgroud)
FileOutputStream f = new FileOutputStream(new File("/sdcard/output.raw"));
f.write(imgData);
f.flush();
f.close();
Run Code Online (Sandbox Code Playgroud)
谢谢!
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
}
Run Code Online (Sandbox Code Playgroud)
我相信Apache Commons IO有用于完成这类工作的类,所以你不需要自己编写它.