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

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

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

 1 package eg2;
 2  
 3 import java.io.File;
 4 import java.io.IOException;
 5 import java.nio.file.Files;
 6 import java.util.Scanner;
 7  
 8 /******************
 9  * 文件的复制
10  *******************/
11  
12 public class Test2_3 {
13  
14     public static void main(String[] args) throws IOException {
15         // TODO Auto-generated method stub
16         @SuppressWarnings("resource")
17         Scanner sc = new Scanner(System.in);
18         System.out.println("请输入指定文件夹路径:");
19         String oldpath = sc.next();
20         System.out.println("请输入目标文件夹路径:");
21         String newpath = sc.next();
22         System.out.println("请输入要复制的文件名:");
23         String filename = sc.next();
24         copy(filename, oldpath, newpath);
25         System.out.println("复制完成!");
26     }
27  
28     private static void copy(String filename, String oldpath, String newpath) throws IOException {
29         // TODO Auto-generated method stub
30         File oldpaths = new File(oldpath + "/" + filename);
31         File newpaths = new File(newpath + "/" + filename);
32         if (!newpaths.exists()) {
33             Files.copy(oldpaths.toPath(), newpaths.toPath());
34         } else {
35             newpaths.delete();
36             Files.copy(oldpaths.toPath(), newpaths.toPath());
37         }
38  
39         // String newfile = "";
40         // newfile += newpaths;
41         // FileInputStream in = new FileInputStream(oldpaths);
42         // File file = new File(newfile);
43         // if (!file.exists()) {
44         // file.createNewFile();
45         // }
46         // FileOutputStream out = new FileOutputStream(newpaths);
47         // byte[] buffer = new byte[1024];
48         // int c;
49         // while ((c = in.read(buffer)) != -1) {
50         // for (int i = 0; i < c; i++) {
51         // out.write(buffer[i]);
52         // }
53         // }
54         // in.close();
55         // out.close();
56     }
57  
58 }

 

转载于:https://www.cnblogs.com/mengweihong/p/11305112.html

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值