我正在编写一个Android应用程序,它将资产中的文件复制到设备驱动器上的一个文件中(没有权限问题,字节从资产到驱动器).我需要复制的文件大于1 MB,因此我将其拆分为多个文件,然后将其复制为:
try {
out = new FileOutputStream(destination);
for (InputStream file : files /* InputStreams from assets */) {
copyFile(file);
file.close();
}
out.close();
System.out.println(bytesCopied); // shows 8716288
System.out.println(new File(destination).length()); // shows 8749056
} catch (IOException e) {
Log.e("ERROR", "Cannot copy file.");
return;
}
Run Code Online (Sandbox Code Playgroud)
然后,copyFile()方法:
private void copyFile(InputStream file) throws IOException {
byte[] buffer = new byte[16384];
int length;
while ((length = file.read(buffer)) > 0) {
out.write(buffer);
bytesCopied += length;
out.flush();
}
}
Run Code Online (Sandbox Code Playgroud)
目标文件应包含的正确字节数是8716288(这是我查看原始文件时获得的,如果我计算Android应用程序中的写入字节数),但new File(destination).length()显示为8749056.
我究竟做错了什么?
文件大小变得太大,因为您没有length为每次写入写入字节,实际上每次都写入整个缓冲区,这是buffer.length()字节长.
您应该使用write(byte[] b, int off, int len)重载来指定要在每次迭代中写入的缓冲区中的字节数.
| 归档时间: |
|
| 查看次数: |
168 次 |
| 最近记录: |