android:将一个文件复制到另一个文件的更快解决方案

时间:2012-05-24 12:09:28

标签: java android filechannel

我正在使用BufferedInputStream复制文件。 我在循环中复制byte []。 这对于大文件来说非常慢。

我看到了FileChannel结构。我也试过用它。我想知道FileChannel是否比使用IOSTream更好。在我的测试中,我无法看到主要的性能提升。

还是有其他更好的解决方案。

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

使用fileChannel

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);
        }

3 个答案:

答案 0 :(得分:1)

我认为由于硬盘/ SD卡速度可能是瓶颈,性能无法显着提升。

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

这不是更快,但感觉更快,因为你不必等待复制操作的完成。

此解决方案仅适用于您的应用在启动后不立即需要结果的情况。

有关详细信息,请参阅AsyncTask

答案 1 :(得分:0)

必须在循环中调用

transferFrom()。它不能保证在一次通话中转移全部金额。

答案 2 :(得分:0)

我终于使用覆盖和重命名来完成它。使用Randomfile覆盖前x个字节。然后重命名该文件。现在它的速度要快得多,所有文件的大小都要花费相同的时间。

感谢。