溫馨提示×

java如何實(shí)現(xiàn)文件復(fù)制功能

小億
82
2024-03-19 16:40:35
欄目: 編程語言

在Java中,可以使用FileInputStream和FileOutputStream來實(shí)現(xiàn)文件復(fù)制功能。以下是一個(gè)簡單的示例代碼:

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

public class FileCopy {

    public static void main(String[] args) {
        String sourceFile = "source.txt";
        String destFile = "destination.txt";

        try {
            File source = new File(sourceFile);
            File dest = new File(destFile);

            FileInputStream fis = new FileInputStream(source);
            FileOutputStream fos = new FileOutputStream(dest);

            byte[] buffer = new byte[1024];
            int length;
            while ((length = fis.read(buffer)) > 0) {
                fos.write(buffer, 0, length);
            }

            fis.close();
            fos.close();

            System.out.println("File copied successfully.");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

在這個(gè)示例中,首先指定源文件和目標(biāo)文件的路徑,然后創(chuàng)建FileInputStream和FileOutputStream來讀取源文件和寫入目標(biāo)文件。接著,創(chuàng)建一個(gè)緩沖區(qū)數(shù)組,通過循環(huán)讀取源文件內(nèi)容并將內(nèi)容寫入目標(biāo)文件。最后關(guān)閉輸入流和輸出流,并輸出文件復(fù)制成功的信息。

0