在我们的实际工作中经常会用到的文件操作,再此,将工作中碰到的做一个记录,以便日后查看。
1、复制文件夹到新文件夹下
1 /** 2 * 复制文件夹下所有文件到指定路径 3 *@param oldPath 4 *@param newPath 5 *@author qin_hqing 6 *@date 2015年7月6日 上午11:59:33 7 *@comment 8 */ 9 public static void copyFolder(String oldPath, String newPath) { 10 11 try { 12 (new File(newPath)).mkdirs(); // 如果文件夹不存在 则建立新文件夹 13 File a = new File(oldPath); 14 String[] file = a.list(); //获取文件夹下所有文件 15 File temp = null; 16 for (int i = 0; i < file.length; i++) { 17 if (oldPath.endsWith(File.separator)) { //判断传入的路径是否存在路径分隔符,若没有则加上 18 temp = new File(oldPath + file[i]); 19 } else { 20 temp = new File(oldPath + File.separator + file[i]); 21 } 22 23 if (temp.isFile()) { //文件,则复制到目标目录 24 FileInputStream input = new FileInputStream(temp); 25 FileOutputStream output = new FileOutputStream(newPath 26 + File.separator + (temp.getName()).toString()); 27 byte[] b = new byte[1024 * 5]; 28 int len; 29 while ((len = input.read(b)) != -1) { 30 output.write(b, 0, len); 31 } 32 output.flush(); 33 output.close(); 34 input.close(); 35 } 36 if (temp.isDirectory()) {// 如果是子文件夹 37 copyFolder(oldPath + File.separator + file[i], newPath + File.separator + file[i]); 38 } 39 } 40 } catch (Exception e) { 41 System.out.println("复制整个文件夹内容操作出错"); 42 e.printStackTrace(); 43 44 } 45 46 }