3

bufferedInputStream大きなバイナリ ファイルを使用しbufferedOutputStreamて、ソース ファイルから宛先ファイルにコピーしたいと考えています。

これが私のコードです:

   byte[] buffer = new byte[1000];        
    try {
        FileInputStream fis = new FileInputStream(args[0]);
        BufferedInputStream bis = new BufferedInputStream(fis);

        FileOutputStream fos = new FileOutputStream(args[1]);
        BufferedOutputStream bos = new BufferedOutputStream(fos);

        int numBytes;
        while ((numBytes = bis.read(buffer))!= -1)
        {
            bos.write(buffer);
        }
        //bos.flush();
        //bos.write("\u001a");

        System.out.println(args[0]+ " is successfully copied to "+args[1]);

        bis.close();
        bos.close();
    } catch (IOException e)
    {
        e.printStackTrace();
    }

正常にコピーできますが、使用します

cmp src dest

コマンド ラインで 2 つのファイルを比較します。エラーメッセージ

cmp: ファイルの EOF

が表示されます。どこが間違っていたのかわかるでしょうか?

4

4 に答える 4

9

これは間違いです:

bos.write(buffer);

データをその一部にしか読み取っていない場合でも、バッファー全体を書き込んでいます。以下を使用する必要があります。

bos.write(buffer, 0, numBytes);

また、Java 7 以降を使用している場合は try-with-resources を使用するか、それ以外の場合はclose呼び出しをfinallyブロックに入れることをお勧めします。

Steffenが指摘しFiles.copyているように、それが利用できる場合は、より簡単なアプローチです。

于 2015-01-23T10:27:46.507 に答える
2

Java 8 を使用している場合は、このFiles.copy(Path source, Path target)方法を試してください。

于 2015-01-23T10:23:50.770 に答える
2

あなたはあなたを閉じる必要がありFileOutputStreamますFileInputStream

また、次のように FileChannel を使用してコピーすることもできます

FileChannel from = new FileInputStream(sourceFile).getChannel();
FileChanngel to = new FileOutputStream(destFile).getChannel();
to.transferFrom(from, 0, from.size());
from.close();
to.close();
于 2015-01-23T10:27:56.793 に答える
0

apatch-commons ライブラリの IOUtils を使用できます

私はあなたが必要とする大きな機能をコピーすると思います

于 2015-01-23T10:33:27.753 に答える