java实现文件复制、剪切文件和删除示例
复制代码 代码如下: import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; /** * Java实现文件复制、剪切、删除操作 * 文件指文件或文件夹 * 文件分割符统一用"" */ public class FileOperateDemo { /** * 复制文件或文件夹 * @param srcPath 源文件或源文件夹的路径 * @param destDir 目标文件所在的目录 * @return */ public static boolean copyGeneralFile(String srcPath,String destDir) { boolean flag = false; File file = new File(srcPath); if(!file.exists()) { // 源文件或源文件夹不存在 return false; } if(file.isFile()) { // 文件复制 flag = copyFile(srcPath,destDir); } else if(file.isDirectory()) { // 文件夹复制 flag = copyDirectory(srcPath,destDir); } return flag; } /** * 默认的复制文件方法,默认会覆盖目标文件夹下的同名文件 * @param srcPath * 源文件绝对路径 * @param destDir * 目标文件所在目录 * @return boolean */ public static boolean copyFile(String srcPath,String destDir) { return copyFile(srcPath,destDir,true/**overwriteExistFile*/); // 默认覆盖同名文件 } /** * 默认的复制文件夹方法,默认会覆盖目标文件夹下的同名文件夹 * @param srcPath 源文件夹路径 * @param destPath 目标文件夹所在目录 * @return boolean */ public static boolean copyDirectory(String srcPath,String destDir) { return copyDirectory(srcPath,true/**overwriteExistDir*/); } /** * 复制文件到目标目录 * @param srcPath * 源文件绝对路径 * @param destDir * 目标文件所在目录 * @param overwriteExistFile * 是否覆盖目标目录下的同名文件 * @return boolean */ public static boolean copyFile(String srcPath,String destDir,boolean overwriteExistFile) { boolean flag = false; File srcFile = new File(srcPath); if (!srcFile.exists() || !srcFile.isFile()) { // 源文件不存在 return false; } //获取待复制文件的文件名 String fileName = srcFile.getName(); String destPath = destDir + File.separator +fileName; File destFile = new File(destPath); if (destFile.getAbsolutePath().equals(srcFile.getAbsolutePath())) { // 源文件路径和目标文件路径重复 return false; } if(destFile.exists() && !overwriteExistFile) { // 目标目录下已有同名文件且不允许覆盖 return false; } File destFileDir = new File(destDir); if(!destFileDir.exists() && !destFileDir.mkdirs()) { // 目录不存在并且创建目录失败直接返回 return false; } try { FileInputStream fis = new FileInputStream(srcPath); FileOutputStream fos = new FileOutputStream(destFile); byte[] buf = new byte[1024]; int c; while ((c = fis.read(buf)) != -1) { fos.write(buf,c); } fos.flush(); fis.close(); fos.close(); flag = true; } catch (IOException e) { e.printStackTrace(); } return flag; } /** * * @param srcPath 源文件夹路径 * @param destPath 目标文件夹所在目录 * @return */ public static boolean copyDirectory(String srcPath,boolean overwriteExistDir) { if(destDir.contains(srcPath)) return false; boolean flag = false; flag = file.delete(); (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |