国产av日韩一区二区三区精品,成人性爱视频在线观看,国产,欧美,日韩,一区,www.成色av久久成人,2222eeee成人天堂

ホームページ Java &#&ベース Javaでファイルをコピーする方法の4つの例

Javaでファイルをコピーする方法の4つの例

Nov 29, 2019 pm 05:38 PM
java

Javaでファイルをコピーする方法の4つの例

java復制文件的4種方法:(推薦:java視頻教程

一、使用FileStreams復制

這是最經(jīng)典的方式將一個文件的內(nèi)容復制到另一個文件中。 使用FileInputStream讀取文件A的字節(jié),使用FileOutputStream寫入到文件B。 這是第一個方法的代碼:

private static void copyFileUsingFileStreams(File source, File dest)
        throws IOException {    
    InputStream input = null;    
    OutputStream output = null;    
    try {
           input = new FileInputStream(source);
           output = new FileOutputStream(dest);        
           byte[] buf = new byte[1024];        
           int bytesRead;        
           while ((bytesRead = input.read(buf)) != -1) {
               output.write(buf, 0, bytesRead);
           }
    } finally {
        input.close();
        output.close();
    }
}

正如你所看到的我們執(zhí)行幾個讀和寫操作try的數(shù)據(jù),所以這應該是一個低效率的,下一個方法我們將看到新的方式。

二、使用FileChannel復制

Java NIO包括transferFrom方法,根據(jù)文檔應該比文件流復制的速度更快。 這是第二種方法的代碼:

private static 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();
    }
}

三、使用Commons IO復制

Apache Commons IO提供拷貝文件方法在其FileUtils類,可用于復制一個文件到另一個地方。它非常方便使用Apache Commons FileUtils類時,您已經(jīng)使用您的項目。基本上,這個類使用Java NIO FileChannel內(nèi)部。 這是第三種方法的代碼:

private static void copyFileUsingApacheCommonsIO(File source, File dest)
         throws IOException {
     FileUtils.copyFile(source, dest);
 }

該方法的核心代碼如下:

private static void doCopyFile(File srcFile, File destFile, boolean preserveFileDate) throws IOException {
        if (destFile.exists() && destFile.isDirectory()) {
            throw new IOException("Destination '" + destFile + "' exists but is a directory");
        }

        FileInputStream fis = null;
        FileOutputStream fos = null;
        FileChannel input = null;
        FileChannel output = null;
        try {
            fis = new FileInputStream(srcFile);
            fos = new FileOutputStream(destFile);
            input  = fis.getChannel();
            output = fos.getChannel();
            long size = input.size();
            long pos = 0;
            long count = 0;
            while (pos < size) {
                count = size - pos > FILE_COPY_BUFFER_SIZE ? FILE_COPY_BUFFER_SIZE : size - pos;
                pos += output.transferFrom(input, pos, count);
            }
        } finally {
            IOUtils.closeQuietly(output);
            IOUtils.closeQuietly(fos);
            IOUtils.closeQuietly(input);
            IOUtils.closeQuietly(fis);
        }

        if (srcFile.length() != destFile.length()) {
            throw new IOException("Failed to copy full contents from &#39;" +
                    srcFile + "&#39; to &#39;" + destFile + "&#39;");
        }
        if (preserveFileDate) {
            destFile.setLastModified(srcFile.lastModified());
        }
    }

由此可見,使用Apache Commons IO復制文件的原理就是上述第二種方法:使用FileChannel復制

四、使用Java7的Files類復制

如果你有一些經(jīng)驗在Java 7中你可能會知道,可以使用復制方法的Files類文件,從一個文件復制到另一個文件。 這是第四個方法的代碼:

 private static void copyFileUsingJava7Files(File source, File dest)
         throws IOException {    
         Files.copy(source.toPath(), dest.toPath());
 }

五、測試

現(xiàn)在看到這些方法中的哪一個是更高效的,我們會復制一個大文件使用每一個在一個簡單的程序。 從緩存來避免任何性能明顯我們將使用四個不同的源文件和四種不同的目標文件。 讓我們看一下代碼:

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.channels.FileChannel;
import java.nio.file.Files;
import org.apache.commons.io.FileUtils;

public class CopyFilesExample {

    public static void main(String[] args) throws InterruptedException,
            IOException {

        File source = new File("C:\\Users\\nikos7\\Desktop\\files\\sourcefile1.txt");
        File dest = new File("C:\\Users\\nikos7\\Desktop\\files\\destfile1.txt");

        // copy file using FileStreamslong start = System.nanoTime();
        long end;
        copyFileUsingFileStreams(source, dest);
        System.out.println("Time taken by FileStreams Copy = "
                + (System.nanoTime() - start));

        // copy files using java.nio.FileChannelsource = new File("C:\\Users\\nikos7\\Desktop\\files\\sourcefile2.txt");
        dest = new File("C:\\Users\\nikos7\\Desktop\\files\\destfile2.txt");
        start = System.nanoTime();
        copyFileUsingFileChannels(source, dest);
        end = System.nanoTime();
        System.out.println("Time taken by FileChannels Copy = " + (end - start));

        // copy file using Java 7 Files classsource = new File("C:\\Users\\nikos7\\Desktop\\files\\sourcefile3.txt");
        dest = new File("C:\\Users\\nikos7\\Desktop\\files\\destfile3.txt");
        start = System.nanoTime();
        copyFileUsingJava7Files(source, dest);
        end = System.nanoTime();
        System.out.println("Time taken by Java7 Files Copy = " + (end - start));

        // copy files using apache commons iosource = new File("C:\\Users\\nikos7\\Desktop\\files\\sourcefile4.txt");
        dest = new File("C:\\Users\\nikos7\\Desktop\\files\\destfile4.txt");
        start = System.nanoTime();
        copyFileUsingApacheCommonsIO(source, dest);
        end = System.nanoTime();
        System.out.println("Time taken by Apache Commons IO Copy = "
                + (end - start));

    }

    private static void copyFileUsingFileStreams(File source, File dest)
            throws IOException {
        InputStream input = null;
        OutputStream output = null;
        try {
            input = new FileInputStream(source);
            output = new FileOutputStream(dest);
            byte[] buf = new byte[1024];
            int bytesRead;
            while ((bytesRead = input.read(buf)) > 0) {
                output.write(buf, 0, bytesRead);
            }
        } finally {
            input.close();
            output.close();
        }
    }

    private static 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();
        }
    }

    private static void copyFileUsingJava7Files(File source, File dest)
            throws IOException {
        Files.copy(source.toPath(), dest.toPath());
    }

    private static void copyFileUsingApacheCommonsIO(File source, File dest)
            throws IOException {
        FileUtils.copyFile(source, dest);
    }

}

輸出:

Time taken by FileStreams Copy = 127572360
Time taken by FileChannels Copy = 10449963
Time taken by Java7 Files Copy = 10808333
Time taken by Apache Commons IO Copy = 17971677

正如您可以看到的FileChannels拷貝大文件是最好的方法。如果你處理更大的文件,你會注意到一個更大的速度差。?

更多java知識請關注java基礎教程欄目。

以上がJavaでファイルをコピーする方法の4つの例の詳細內(nèi)容です。詳細については、PHP 中國語 Web サイトの他の関連記事を參照してください。

このウェブサイトの聲明
この記事の內(nèi)容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰屬します。このサイトは、それに相當する法的責任を負いません。盜作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。

ホットAIツール

Undress AI Tool

Undress AI Tool

脫衣畫像を無料で

Undresser.AI Undress

Undresser.AI Undress

リアルなヌード寫真を作成する AI 搭載アプリ

AI Clothes Remover

AI Clothes Remover

寫真から衣服を削除するオンライン AI ツール。

Clothoff.io

Clothoff.io

AI衣類リムーバー

Video Face Swap

Video Face Swap

完全無料の AI 顔交換ツールを使用して、あらゆるビデオの顔を簡単に交換できます。

ホットツール

メモ帳++7.3.1

メモ帳++7.3.1

使いやすく無料のコードエディター

SublimeText3 中國語版

SublimeText3 中國語版

中國語版、とても使いやすい

ゼンドスタジオ 13.0.1

ゼンドスタジオ 13.0.1

強力な PHP 統(tǒng)合開発環(huán)境

ドリームウィーバー CS6

ドリームウィーバー CS6

ビジュアル Web 開発ツール

SublimeText3 Mac版

SublimeText3 Mac版

神レベルのコード編集ソフト(SublimeText3)

JDBCを使用してJavaのトランザクションを処理する方法は? JDBCを使用してJavaのトランザクションを処理する方法は? Aug 02, 2025 pm 12:29 PM

JDBCトランザクションを正しく処理するには、最初に自動コミットモードをオフにし、次に複數(shù)の操作を?qū)g行し、結果に応じて最終的にコミットまたはロールバックする必要があります。 1。CONN.SETAUTOCOMMIT(FALSE)を呼び出して、トランザクションを開始します。 2。挿入や更新など、複數(shù)のSQL操作を?qū)g行します。 3。すべての操作が成功した場合はconn.commit()を呼び出し、データの一貫性を確保するために例外が発生した場合はconn.rollback()を呼び出します。同時に、リソースを使用してリソースを管理し、例外を適切に処理し、接続を密接に接続するために、接続の漏れを避けるために使用する必要があります。さらに、接続プールを使用してセーブポイントを設定して部分的なロールバックを達成し、パフォーマンスを改善するためにトランザクションを可能な限り短く保つことをお勧めします。

Java仮想マシン(JVM)內(nèi)部の理解 Java仮想マシン(JVM)內(nèi)部の理解 Aug 01, 2025 am 06:31 AM

thejvmenablesjavaの「writeonce、runany where "capabilitybyexcuting byteCodeThethermainComponents:1。theClassLoaderSubSystemloads、links、andinitializes.classfilesusingbootStrap、拡張、およびアプリケーションクラスローロー、

Javaでカレンダーを操作する方法は? Javaでカレンダーを操作する方法は? Aug 02, 2025 am 02:38 AM

Java.Timeパッケージのクラスを使用して、古い日付とカレンダーのクラスを置き換えます。 2。LocalDate、LocalDateTime、LocalTimeを通じて現(xiàn)在の日付と時刻を取得します。 3。of()メソッドを使用して特定の日付と時刻を作成します。 4.プラス/マイナスメソッドを使用して、時間を不正に増加させて短縮します。 5. ZonedDateTimeとZoneIDを使用して、タイムゾーンを処理します。 6。DateTimeFormatterを介したフォーマットおよび解析の文字列。 7.インスタントを使用して、必要に応じて古い日付型と互換性があります?,F(xiàn)代のJavaでの日付処理は、java.timeapiを使用することを優(yōu)先する必要があります。

Javaフレームワークの比較:Spring Boot vs Quarkus vs Micronaut Javaフレームワークの比較:Spring Boot vs Quarkus vs Micronaut Aug 04, 2025 pm 12:48 PM

Pre-formanceTartuptimeMemoryusage、quarkusandmicronautleadduetocopile-timeprocessingingandgraalvsupport、withquarkusoftentylightbetterine serverlessシナリオ。

ネットワークポートとファイアウォールの理解 ネットワークポートとファイアウォールの理解 Aug 01, 2025 am 06:40 AM

ネットワークポートアンドファイアワルクトグテルトエナブルコマニケーションwhiledensuringsecurity.1.networksarevirtualendpointsnumbered0–655 35、withwell-knownportslike80(http)、443(https)、22(ssh)、および25(smtp)識別pecificservices.2.portsoperateovertcp(信頼できる、c

Garbage CollectionはJavaでどのように機能しますか? Garbage CollectionはJavaでどのように機能しますか? Aug 02, 2025 pm 01:55 PM

JavaのGarbage Collection(GC)は、メモリを自動的に管理するメカニズムであり、到達不可能なオブジェクトを取り戻すことでメモリ漏れのリスクを軽減します。 1.GCルートオブジェクトからのオブジェクトのアクセシビリティ(スタック変數(shù)、アクティブスレッド、靜的フィールドなど)、および到達不可能なオブジェクトはゴミとしてマークされています。 2。マーククリアリングアルゴリズムに基づいて、すべての到達可能なオブジェクトをマークし、マークのないオブジェクトをクリアします。 3.世代の収集戦略を採用する:新世代(Eden、S0、S1)は頻繁にMinorGCを?qū)g行します。高齢者のパフォーマンスは少なくなりますが、MajorGCを?qū)g行するのに時間がかかります。 Metaspaceはクラスメタデータを保存します。 4。JVMはさまざまなGCデバイスを提供します。SerialGCは小さなアプリケーションに適しています。 ParallelGCはスループットを改善します。 CMSが減少します

Javaビルドツールの比較:Maven vs. Gradle Javaビルドツールの比較:Maven vs. Gradle Aug 03, 2025 pm 01:36 PM

gradleisthebetterchoiceformostnewprojectoitssuperorfficability、performance、andmoderntoolingsupport.1.gradle’sgroovy/kotlindslismoreconciseandexpressiveethanmaven’sverboseml.2.gradleorformsmavenbenbumebutedwitedwitedwitedspedexは

説明された延期聲明の例で進みます 説明された延期聲明の例で進みます Aug 02, 2025 am 06:26 AM

Deferは、クリーニングリソースなど、関數(shù)が戻る前に指定された操作を?qū)g行するために使用されます。パラメーターは、延期時にすぐに評価され、関數(shù)は最後のファーストアウト(LIFO)の順に実行されます。 1.複數(shù)の債務は、宣言の逆の順序で実行されます。 2.ファイルの閉鎖などの安全なクリーニングに一般的に使用されます。 3。指定された返品値を変更できます。 4.回復に適したパニックが発生した場合でも実行されます。 5。リソースの漏れを防ぐために、ループで延期の亂用を避けます。正しい使用により、コードのセキュリティと読みやすさが向上します。

See all articles