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

标签 java android filechannel

我正在使用 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/

相关文章:

android - 测试协程中可观察到的场变化

android - Fedor 的延迟加载问题

java - 我应该关闭 FileChannel 吗?

Java Swing : keeping the event handling maintanable

android - 删除任何 View 时,不会调用 PageAdapter 的 destroyItem 函数

android - 通过 MappedByteBuffer 将原始 VBO 数据加载到 OpenGL(不工作)

java - 用 Java 将 FloatBuffer 或 Float(float) 数组写入文件的最快方法

java - 平滑的网格运动

java - 为什么 Maven javadoc 失败并出现错误 "cannot read options"?

java - 为什么我无法在 AsyncTask 中为另一个类的 ListView 设置适配器?