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