gpt4 book ai didi

java - 安卓 : faster solution to copying one file to another

转载 作者:行者123 更新时间:2023-12-01 15:22:13 25 4
gpt4 key购买 nike

我正在使用 BufferedInputStream 复制文件。我在循环中复制字节[]。对于大文件来说这相当慢。

我看到了 FileChannel 结构。我也尝试使用这个。我想知道 FileChannel 是否比使用 IOSTreams 更好。在我的测试过程中,我没有看到重大的性能改进。

或者还有其他更好的解决方案吗?

我的要求是修改src文件的前1000字节并复制到目标文件,将src文件的其余字节复制到目标文件。

使用文件 channel

private  void copyFile(File sourceFile, File destFile,byte[] buffer,int srcOffset, int destOffset) {
try {
if (!sourceFile.exists()) {
return;
}
if (!destFile.exists()) {
destFile.createNewFile();
}
FileChannel source = null;
FileChannel destination = null;
source = new FileInputStream(sourceFile).getChannel();
source.position(srcOffset);
destination = new FileOutputStream(destFile).getChannel();
destination.write(ByteBuffer.wrap(buffer));
if (destination != null && source != null) {
destination.transferFrom(source, destOffset, source.size()-srcOffset);
}
if (source != null) {
source.close();
}
if (destination != null) {
destination.close();
}

} catch (Exception ex) {
ex.printStackTrace();
}
}

使用 I/O 流

while ((count = random.read(bufferData)) != -1) {

fos.write(bufferData, 0, count);
}

最佳答案

我认为性能不会显着提高,因为硬盘/SD 卡速度可能是瓶颈。

但是,创建一个执行复制的后台任务可能会有所帮助。

这并不是真正更快,但感觉更快,因为您不必等待复制操作完成。

仅当您的应用启动后不需要立即得到结果时,此解决方案才有效。

详情参见 AsyncTask

关于java - 安卓 : faster solution to copying one file to another,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10737234/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com