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 }

 

posted @ 2019-08-05 19:41  随灬影  阅读(10905)  评论(0编辑  收藏  举报