首頁 > Java > java教程 > 主體

案例研究:複製文件

PHPz
發布: 2024-07-16 16:27:20
原創
1103 人瀏覽過

本節開發了一個用於複製檔案的有用實用程式。在本節中,您將學習如何編寫允許使用者複製檔案的程式。使用者需要使用以下命令提供原始檔案和目標檔案作為命令列參數:

java 複製來源目標

程式將來源檔案複製到目標檔案並顯示檔案中的位元組數。如果來源檔案不存在或目標檔案已存在,程式應警告使用者。程式的運行範例如下圖所示。

Image description

要將來源文件的內容複製到目標文件,適合使用輸入流從來源文件讀取字節,並使用輸出流將位元組發送到目標文件,而不管文件的內容如何。來源檔案和目標檔案是從命令列指定的。為來源檔案建立一個 InputFileStream 並為目標檔案建立一個 OutputFileStream。使用 read() 方法從輸入流讀取一個位元組,然後使用 write(b) 方法將該位元組寫入輸出流。使用 BufferedInputStreamBufferedOutputStream 來提高效能。下面的程式碼給出了問題的解決方案。

package demo;
import java.io.*;

public class Copy {
    public static void main(String[] args) throws IOException {
        // Check command-line parameter usage
        if(args.length != 2) {
            System.out.println("Usage: java Copy sourceFile targetfile");
            System.exit(1);
        }

        // Check if source file exists
        File sourceFile = new File(args[0]);
        if(!sourceFile.exists()) {
            System.out.println("Source file " + args[0] + " does not exist");
            System.exit(2);
        }

        // Check if source file exists
        File targetFile = new File(args[1]);
        if(!targetFile.exists()) {
            System.out.println("Target file " + args[1] + " already exist");
            System.exit(3);
        }

        try(
            // Create an input  stream
                BufferedInputStream input = new BufferedInputStream(new FileInputStream(sourceFile));

                // Create an output stream
                BufferedOutputStream output = new BufferedOutputStream(new FileOutputStream(targetFile));
            ) {
            // COntinuously read a byte from input and write it to output
            int r, numberOfBytesCopied = 0;
            while((r = input.read()) != -1) {
                output.write((byte)r);
                numberOfBytesCopied++;
            }

            // Display the file size
            System.out.println(numberOfBytesCopied + " bytes copied");
        }
    }
}

登入後複製

程式首先檢查使用者是否在第 7-10 行從命令列傳遞了兩個必要的參數。

程式使用File類別來檢查來源檔案和目標檔案是否存在。如果原始檔案不存在(第 14-17 行)或目標檔案已存在(第 20-24 行),則程式結束。

第28 行使用包裹在FileInputStream 上的BufferedInputStream 建立輸入流,並使用包裹在FileOutputStreamBuffereded 。 🎜> 第 31 行。 表達式

((r = input.read()) != -1)

(第 35 行)從 讀取一個位元組 input.read()
,將其賦值給r,並檢查是否為-1。輸入值 -1 表示檔案結束。程式不斷從輸入流讀取位元組並將它們傳送到輸出流,直到讀取完所有位元組。

以上是案例研究:複製文件的詳細內容。更多資訊請關注PHP中文網其他相關文章!

來源:dev.to
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!