温馨提示×

java如何实现文件复制功能

小亿
82
2024-03-19 16:40:35
栏目: 编程语言

在Java中,可以使用FileInputStream和FileOutputStream来实现文件复制功能。以下是一个简单的示例代码:

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

在这个示例中,首先指定源文件和目标文件的路径,然后创建FileInputStream和FileOutputStream来读取源文件和写入目标文件。接着,创建一个缓冲区数组,通过循环读取源文件内容并将内容写入目标文件。最后关闭输入流和输出流,并输出文件复制成功的信息。

0