温馨提示×

java怎么复制文件到指定目录

小亿
107
2024-01-03 12:37:06
栏目: 编程语言

要在Java中复制文件到指定目录,可以使用Java IO库中的File类和InputStream/OutputStream类。

以下是一个简单的示例代码:

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 sourceFilePath = "path/to/source/file";
        String destinationFilePath = "path/to/destination/file";

        File sourceFile = new File(sourceFilePath);
        File destinationFile = new File(destinationFilePath);

        try {
            copyFile(sourceFile, destinationFile);
            System.out.println("文件复制成功!");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void copyFile(File source, File destination) throws IOException {
        FileInputStream inputStream = new FileInputStream(source);
        FileOutputStream outputStream = new FileOutputStream(destination);

        byte[] buffer = new byte[1024];
        int length;

        while ((length = inputStream.read(buffer)) > 0) {
            outputStream.write(buffer, 0, length);
        }

        inputStream.close();
        outputStream.close();
    }
}

在代码中,将源文件路径和目标文件路径替换为实际的文件路径。然后,通过调用copyFile方法来复制文件。该方法使用FileInputStream从源文件读取数据,并使用FileOutputStream将数据写入目标文件。

请确保源文件存在,并且具有读取权限,目标目录存在并且具有写入权限。

0