/** * 拷贝文件 * * @param src String 原文件路径 如:c:/aaa.txt * @param dest String 复制后路径 如:g:/bbb.txt * @return String 空串"":成功,否则为失败的信息 */ public static String copyFile(String src, String dest) { BufferedInputStream input = null; BufferedOutputStream output = null; if(src == null) { return "源文件名称不能为空"; } File srcFile = new File(src); if(!srcFile.exists() || !srcFile.isFile()) { return "源文件不存在或不是一个有效文件."; } if(dest == null) { return "目的文件名不能为空"; } dest = dest.replaceAll("", "/"); int dotIndex = dest.lastIndexOf("/"); if(dotIndex > 0) { String destPath = dest.substring(0, dotIndex); File destFile = new File(destPath); if(!destFile.exists()) { destFile.mkdirs(); } } else return "目的文件名不正确, destName=" + dest; } try { int byteLen; byte[] byteArr = new byte[INT_READLEN]; input = new BufferedInputStream(new FileInputStream(src)); output = new BufferedOutputStream(new FileOutputStream(dest)); while((byteLen = input.read(byteArr)) != -1) { output.write(byteArr, 0, byteLen); } } catch(Exception e) { return e.getMessage(); } finally { try { if(input != null) input.close(); } catch(IOException e) { } try { if(output != null) output.close(); } catch(IOException e) { } } return ""; } /** * 拷贝整个文件夹 * * @param srcPath 原文件路径 如:c:/temp * @param destPath 复制后路径 如:g:/tmp/tt * @return String 空串"":成功,否则为失败的信息 */ public static String copyFolder(String srcPath, String destPath) { try { File srcFile = new File(srcPath); if(!srcFile.exists() || !srcFile.isDirectory()) { return "源路径不存在或不是一个有效目录."; } if(!srcPath.endsWith(File.separator)) srcPath += File.separator; File destFile = new File(destPath); if(!destFile.exists()) destFile.mkdirs(); if(!destPath.endsWith(File.separator)) destPath += File.separator; String[] fileNames = srcFile.list(); for(int i = 0; i < fileNames.length; i++) { File tmpFile = new File(srcPath + fileNames[i]); if(tmpFile.isFile()) { String msg = copyFile(srcPath + fileNames[i], destPath + fileNames[i]); if(msg.length() > 0) return msg; } else if(tmpFile.isDirectory()) { copyFolder(srcPath + fileNames[i], destPath + fileNames[i]); } } } catch(Exception e) { return "复制文件夹出错."; } return ""; }