怎样用Java复制一个文件到指定目录?

  1. import java.io.*;
  2. public class CopyFile {
  3. public static void main(String[] args) {
  4. try{
  5. FileInputStream input=new FileInputStream("f://downloads//kon.jpg");//可替换为任何路径何和文件名
  6. FileOutputStream output=new FileOutputStream("f://kon.jpg");//可替换为任何路径何和文件名
  7. int in=input.read();
  8. while(in!=-1){
  9. output.write(in);
  10. in=input.read();
  11. }
  12. }catch (IOException e){
  13. System.out.println(e.toString());
  14. }
  15. }
可以使用Java文件操作类来实现文件复制功能。以下是一个示例方法: ```java import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; public class FileCopyExample { public static void copyFile(String sourceFilePath, String destinationFolderPath) throws IOException { // 创建源文件对象 File sourceFile = new File(sourceFilePath); // 创建目标文件夹对象 File destinationFolder = new File(destinationFolderPath); // 如果目标文件夹不存在,则创建 if (!destinationFolder.exists()) { destinationFolder.mkdirs(); } // 创建目标文件对象 File destinationFile = new File(destinationFolder, sourceFile.getName()); // 创建输入流和输出流 FileInputStream fis = new FileInputStream(sourceFile); FileOutputStream fos = new FileOutputStream(destinationFile); // 缓冲区大小(可根据实际情况调整) 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("文件复制成功!"); } public static void main(String[] args) throws IOException { String sourceFilePath = "path/to/source/file.txt"; // 源文件路径 String destinationFolderPath = "path/to/destination/folder"; // 目标文件夹路径 copyFile(sourceFilePath, destinationFolderPath); } } ``` 请将`sourceFilePath`和`destinationFolderPath`替换为实际的源文件路径和目标文件夹路径。调用`copyFile`方法即可完成文件复制操作。
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值