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

   2025-02-13 9830
核心提示:要在Java中复制文件到指定目录,可以使用Java IO库中的File类和InputStream/OutputStream类。以下是一个简单的示例代码:import

要在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将数据写入目标文件。

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

 
 
更多>同类维修知识
推荐图文
推荐维修知识
点击排行
网站首页  |  关于我们  |  联系方式  |  用户协议  |  隐私政策  |  网站留言