为什么输出文件的大小小于原始文件?

时间:2016-03-29 02:47:25

标签: java nio filechannel

我想有效地通过文件渠道传输大文件,因此我使用idx = 1.step # => #<Enumerator: 1:step> arr.each_with_object({}) { |s,h| h["color#{idx.next}"] = s } #=> {"color1"=>"#121427", "color2"=>"#291833", "color3"=>"#4B2E4D", # "color4"=>"#5D072F", "color5"=>"#BB2344", "color6"=>"#ED9F90"} no module named singledispatch来传输文件。

我得到的输出文件不对,这比原始源文件少。这是代码:

java.io.RandomAccessFile

顺便说一下,我的输入文件是一个mkv视频文件,其大小为2937236651字节。虽然我使用java.nio.channels.FileChannel public static void transferByRandomAccess(String inputFile, String outputFile) throws IOException { RandomAccessFile inputRandomAccessFile = null; RandomAccessFile outputRandomAccessFile = null; try { inputRandomAccessFile = new RandomAccessFile(inputFile, "r"); FileChannel inputFileChannel = inputRandomAccessFile.getChannel(); outputRandomAccessFile = new RandomAccessFile(outputFile, "rw"); FileChannel outFileChannel = outputRandomAccessFile.getChannel(); inputFileChannel.transferTo(0, inputFileChannel.size(), outFileChannel); inputFileChannel.force(true); outFileChannel.force(true); } finally { if (outputRandomAccessFile != null) { outputRandomAccessFile.close(); } if (inputRandomAccessFile != null) { inputRandomAccessFile.close(); } } } 复制它,但没有问题。

2 个答案:

答案 0 :(得分:1)

好吧,对于你的新更新,文件大于2GB,操作系统有限制为这种操作制作缓冲区,在这种情况下你需要更新你的应用程序,使其适用于大于2GB的文件

public class Test {

    public static void main(String[] args) throws Exception {
        RandomAccessFile inputRandomAccessFile = null;
        RandomAccessFile outputRandomAccessFile = null;
        try {
            inputRandomAccessFile = new RandomAccessFile("G:\\file1.zip", "r");
            FileChannel inputFileChannel = inputRandomAccessFile.getChannel();
            outputRandomAccessFile = new RandomAccessFile("G:\\file2.zip", "rw");
            FileChannel outFileChannel = outputRandomAccessFile.getChannel();
            long readFileSize = inputFileChannel.size();
            long transferredSize = 0;
            do {
                long count = inputFileChannel.transferTo(transferredSize, inputFileChannel.size(), outFileChannel);
                transferredSize += count;
            } while (transferredSize < readFileSize);

            inputFileChannel.force(true);
            outFileChannel.force(true);
        } finally {
            if (outputRandomAccessFile != null) {
                outputRandomAccessFile.close();
            }
            if (inputRandomAccessFile != null) {
                inputRandomAccessFile.close();
            }
        }
        System.out.println("DONE");
    }
}

答案 1 :(得分:1)

您的复制步骤错误。未指定transferTo()在一次调用中传输整个输入。这就是它返回计数的原因。你必须循环,推进偏移并递减长度,直到没有任何东西要转移。