發現了一個復制文件的源碼自帶的方法,比起流讀寫的方法更簡單了
Files.copy(source, target, options)
源碼部分
public static Path copy(Path source, Path target, CopyOption... options) throws IOException { FileSystemProvider provider = provider(source); if (provider(target) == provider) { // same provider provider.copy(source, target, options); } else { // different providers CopyMoveHelper.copyToForeignTarget(source, target, options); } return target; }
用法也很簡單,源文件,目標文件File 獲取path,在傳入方法,options可以不傳值,參數可以忽略。
例如:D:/a.txt文件要復制到E:/xx/b.txt中,
就要先將兩文件的path得到,這里要求目標文件b.txt文件不存在,存在了就爆錯了。
但是目標文件的路徑必須要有,源代碼方法中沒有創建dir的方法。
eg.
//要確認拷貝的路徑存在 File destDir = new File("E:/xx"); if(!(destDir.exists()&& destDir.isDirectory())) { destDir.mkdirs(); }
File source = new File("D:/a.txt"); File dest = new File("E:/xx/b.txt"); try{ Files.copy(source.toPath(), dest.toPath()); } catch (IOException e){ // TODO Auto-generated catch block e.printStackTrace(); }
復制文件就輕松搞定了
