原生Java代码拷贝目录
生活随笔
收集整理的這篇文章主要介紹了
原生Java代码拷贝目录
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
? ? 拷貝、移動文件(夾),有三方包commons-io可以用,但是有時候有自己的需求,只能使用原生java代碼,這時可以用以下幾種方式進行拷貝:
1、使用系統命令(Linux)調用
? ? 此種方式對操作系統有要求,好處是代碼量少,性能可依賴操作系統優化,但是中間環節不可控。
1 /** 2 * 執行命令 3 */ 4 private static void nativeCall(String... cmd) { 5 ProcessBuilder pb = new ProcessBuilder(cmd); 6 try { 7 pb.redirectErrorStream(true); 8 Process process = pb.start(); 9 InputStream stream = process.getInputStream(); 10 byte[] buff = new byte[4096]; 11 while (stream.read(buff, 0, 4096) != -1) {} 12 stream.close(); 13 } catch (IOException e) { 14 e.printStackTrace(); 15 } 16 } 17 18 // 使用CMD拷貝目錄 19 public static void cmdCopyDir(File src, File des) { 20 if (!des.exists()) { 21 des.mkdirs(); 22 } 23 String[] cmds = new String[] { "sh", "-c", "cp -a \"" + src.getAbsolutePath() + "/.\" \"" + des.getAbsolutePath() + "\"" }; 24 Executor.nativeCall(cmds); 25 } 26 27 // 使用CMD刪除目錄 28 public static void cmdDelDir(File dic) { 29 if (dic.exists() && dic.isDirectory()) { // 判斷是文件還是目錄 30 String[] cmds = new String[] { "sh", "-c", "rm -rf \"" + dic.getAbsolutePath() + "\"" }; 31 Executor.nativeCall(cmds); 32 } 33 }?
2、使用文件通道拷貝
? ? 此種方式是常用的拷貝方式,大部分環節、異常都是可控的,具體的文件復制則使用了通道的方式進行加速。
1 // 拷貝目錄 2 public static void javaCopyDir(File src, File des) throws IOException { 3 if (!des.exists()) { 4 des.mkdirs(); 5 } 6 File[] file = src.listFiles(); 7 for (int i = 0; i < file.length; ++i) { 8 if (file[i].isFile()) { 9 channelCopy(file[i], new File(des.getPath() + "/" + file[i].getName())); 10 } else if (file[i].isDirectory()) { 11 javaCopyDir(file[i], new File(des.getPath() + "/" + file[i].getName()), stoppable); 12 } 13 } 14 } 15 16 // 拷貝文件 17 private static void channelCopy(File src, File des) throws IOException { 18 FileInputStream fi = null; 19 FileOutputStream fo = null; 20 FileChannel in = null; 21 FileChannel out = null; 22 IOException ex = null; 23 try { 24 fi = new FileInputStream(src); 25 fo = new FileOutputStream(des); 26 in = fi.getChannel(); 27 out = fo.getChannel(); 28 in.transferTo(0, in.size(), out); // 連接兩個通道,并且從in通道讀取,然后寫入out通道 29 } finally { 30 try { 31 fi.close(); 32 in.close(); 33 } catch (IOException e) { 34 ex = e; 35 } 36 try { 37 fo.close(); 38 out.close(); 39 } catch (IOException e) { 40 ex = e; 41 } 42 } 43 if (ex != null) { 44 throw ex; 45 } 46 } 47?
?3、原生刪除目錄
1 // 刪除目錄 2 private static void javaDelDir(File dic) throws IOException { 3 if (dic.exists() && dic.isDirectory()) { 4 File delFile[] = dic.listFiles(); 5 if (delFile.length == 0) { // 若目錄下沒有文件則直接刪除 6 dic.delete(); 7 } else { 8 for (File file : delFile) { 9 if (file.isDirectory()) { 10 javaDelDir(file); // 遞歸調用del方法并取得子目錄路徑 11 } 12 file.delete(); // 刪除文件 13 } 14 dic.delete(); 15 } 16 } 17 }? ? 轉載請注明原址:http://www.cnblogs.com/lekko/p/8472353.html?
轉載于:https://www.cnblogs.com/lekko/p/8472353.html
總結
以上是生活随笔為你收集整理的原生Java代码拷贝目录的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 【转】ubuntu 下安装mongodb
- 下一篇: 线程模型、pthread 系列函数 和