java 把文件从一个目录复制到另一个目录。

方法一:简单粗暴,直接使用copy(),如果目标存在,先使用delete()删除,再复制;

方法二:使用输入输出流。(代码注释部分)

 package eg2;
  
 import java.io.File;
 import java.io.IOException;
 import java.nio.file.Files;
 import java.util.Scanner;
  
 /******************
  * 文件的复制
  *******************/
  
 public class Test2_3 {
  
     public static void main(String[] args) throws IOException {
         // TODO Auto-generated method stub
         @SuppressWarnings("resource")
         Scanner sc = new Scanner(System.in);
         System.out.println("请输入指定文件夹路径:");
        String oldpath = sc.next();
         System.out.println("请输入目标文件夹路径:");
         String newpath = sc.next();
         System.out.println("请输入要复制的文件名:");
         String filename = sc.next();
         copy(filename, oldpath, newpath);
         System.out.println("复制完成!");
     }
  
     private static void copy(String filename, String oldpath, String newpath) throws IOException {
         // TODO Auto-generated method stub
         File oldpaths = new File(oldpath + "/" + filename);
         File newpaths = new File(newpath + "/" + filename);
         if (!newpaths.exists()) {
             Files.copy(oldpaths.toPath(), newpaths.toPath());
         } else {
             newpaths.delete();
             Files.copy(oldpaths.toPath(), newpaths.toPath());
         }
  
         // String newfile = "";
         // newfile += newpaths;
         // FileInputStream in = new FileInputStream(oldpaths);
         // File file = new File(newfile);
         // if (!file.exists()) {
         // file.createNewFile();
         // }
         // FileOutputStream out = new FileOutputStream(newpaths);
         // byte[] buffer = new byte[1024];
         // int c;
         // while ((c = in.read(buffer)) != -1) {
         // for (int i = 0; i < c; i++) {
         // out.write(buffer[i]);
         // }
         // }
         // in.close();
         // out.close();
    }
  
 }
  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值