0

同様のコードを使用して、Java で filecopy を使用しています。

private void copyFileUsingFileChannels(File source, File dest) throws IOException {

    FileChannel inputChannel = null;
    FileChannel outputChannel = null;

    try {
        inputChannel = new FileInputStream(source).getChannel();
        outputChannel = new FileOutputStream(dest).getChannel();
        outputChannel.transferFrom(inputChannel, 0, inputChannel.size());
    } finally {
        inputChannel.close();
        outputChannel.close();
    }
}

問題は時々sourcedest同じファイルを指している可能性がありoutputChannel = new FileOutputStream(dest).getChannel();ます.同じハンドル。では、これに対抗する方法は何ですか?

コードに何かを追加する必要があります

if (! (sourcec.getAbsolutePath().equalsIgnoreCase(destinationc.getAbsolutePath()))) 
    copyFiles(sourcec, destinationc);

上記は機能しますか?または、これを処理するより良い方法はありますか?

ありがとう

4

1 に答える 1

1

追加モードなしで開くnew FileOutputStreamと、ファイルが存在する場合は切り捨てられ、存在しない場合は作成されます。(追加モードは役に立ちませんが、ファイルを切り捨てません)ファイルをそれ自体にコピーすることを避けたいので、提案したチェックを行うか、最初の場所。

于 2014-02-05T08:17:19.100 に答える