繁体   English   中英

使用 RandomAccessFile 类写入大文件

[英]Write big files using RandomAccessFile class

我需要将大文件 (GB) 复制到另一个文件(容器)中,我想知道性能和内存使用情况。

像下面这样读取整个源文件:

RandomAccessFile f = new RandomAccessFile(origin, "r");
originalBytes = new byte[(int) f.length()];
f.readFully(originalBytes);

稍后,将所有内容复制到容器中,如下所示:

RandomAccessFile f2 = new RandomAccessFile(dest, "wr");
f2.seek(offset);
f2.write(originalBytes, 0, (int) originalBytes.length);

一切都在内存中,对吗? 那么复制大文件会对内存产生影响并导致 OutOfMemory 异常?

按字节而不是完全读取原始文件字节是否更好? 在这种情况下,我应该如何进行? 先感谢您。

编辑:

按照mehdi maick的回答,我终于找到了解决方案:我可以根据需要使用 RandomAccessFile 作为目标,并且因为 RandomAccessFile 有一个方法“ getChannel ”,它返回一个 FileChannel 我可以将它传递给以下将执行复制的方法(32KB在我想要的目标位置的文件的时间):

     public static void copyFile(File sourceFile, FileChannel destination, int position) throws IOException {
            FileChannel source = null;
            try {
                source = new FileInputStream(sourceFile).getChannel();
                destination.position(position);
                int currentPosition=0;
                while (currentPosition < sourceFile.length())
                    currentPosition += source.transferTo(currentPosition, 32768, destination);
            } finally {
                if (source != null) {
                    source.close();
                }

            }
        }

尝试使用 async nio Channel


    public void copyFile(String src, String target) {
        final String fileName = getFileName(src);
        try (FileChannel from = (FileChannel.open(Paths.get(src), StandardOpenOption.READ));
                FileChannel to = (FileChannel.open(Paths.get(target + "/" + fileName), StandardOpenOption.CREATE_NEW, StandardOpenOption.WRITE))) {
            transfer(from, to, 0l, from.size());
        }
    }

    private String getFileName(final String src) {
        File file = new File(src);
        if (file.isFile()) {
            return file.getName();
        } else {
            throw new RuntimeException("src is not a valid file");
        }
    }

    private void transfer(final FileChannel from, final FileChannel to, long position, long size) throws IOException {
        while (position < size) {
            position += from.transferTo(position, Constants.TRANSFER_MAX_SIZE, to);
        }
    }

这将创建一个读写异步通道,并有效地将数据从第一个传输到后一个。

使用FileInputStreamFileOutputStream读取块/块,例如一次 64k。

如果您需要提高性能,您可以尝试使用线程,一个线程用于读取,另一个线程用于写入。

您还可以使用直接 NIO 缓冲区来提高性能。
参见例如关于何时应该将直接缓冲区与 Java NIO 一起用于网络 I/O 的简单规则?

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM