Java如何複製檔案?

2019-10-16 22:30:10

在java程式設計中,如何將一個檔案複製到另一個檔案?

此範例顯示如何使用BufferedWriter類的read()write()方法將一個檔案的內容複製到另一個檔案中。

package com.yiibai;

import java.io.*;

public class CopyFile {
    public static void main(String[] args) throws Exception {
        String srcfile = "srcfile.txt";
        String destnfile = "destnfile.txt";
        BufferedWriter out1 = new BufferedWriter(new FileWriter(srcfile));
        out1.write("Line 1 : string to be copied\n");
        out1.write("Line 2 : to be copied\n");
        out1.close();
        InputStream in = new FileInputStream(new File(srcfile));
        OutputStream out = new FileOutputStream(new File(destnfile));
        byte[] buf = new byte[1024];
        int len;

        while ((len = in.read(buf)) > 0) {
            out.write(buf, 0, len);
        }
        in.close();
        out.close();
        BufferedReader in1 = new BufferedReader(new FileReader(destnfile));
        String str;

        while ((str = in1.readLine()) != null) {
            System.out.println(str);
        }
        in.close();
    }
}

執行上述範例程式碼,將產生以下結果 -

Line 1 : string to be copied
Line 2 : to be copied

範例-2

以下是將一個檔案複製到另一個檔案的另一個範例。

package com.yiibai;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

public class CopyFile2 {
    public static void main(String[] args) {
        FileInputStream ins = null;
        FileOutputStream outs = null;
        try {
            File infile = new File("F:/worksp/javaexamples/java_files/infile.txt");
            File outfile = new File("F:/worksp/javaexamples/java_files/outfile.txt");
            ins = new FileInputStream(infile);
            outs = new FileOutputStream(outfile);
            byte[] buffer = new byte[1024];
            int length;

            while ((length = ins.read(buffer)) > 0) {
                outs.write(buffer, 0, length);
            }
            ins.close();
            outs.close();
            System.out.println("File copied successfully!!");
        } catch (IOException ioe) {
            ioe.printStackTrace();
        }
    }
}

首先,建立一個檔案:infile.txt,此檔案中的內容就是上面CopyFile2.java檔案的程式碼內容。

執行上述範例程式碼,將產生以下結果 -

File copied successfully!!

在執行完成上面範例程式後,開啟檔案:outfile.txt可以看到其中的內容與infile.txt檔案的內容一樣,說明複製檔案內容成功。