欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

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

程序员文章站 2023-11-15 21:09:16
方法一:简单粗暴,直接使用copy(),如果目标存在,先使用delete()删除,再复制; 方法二:使用输入输出流。(代码注释部分) ......

方法一:简单粗暴,直接使用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 }