파일 복사, 파일 잘라내기 및 삭제 예제의 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, destDir, 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, 0, 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, String destDir, boolean overwriteExistDir) { if(destDir.contains(srcPath)) return false; boolean flag = false; File srcFile = new File(srcPath); if (!srcFile.exists() || !srcFile.isDirectory()) { // 源文件夹不存在 return false; } //获得待复制的文件夹的名字,比如待复制的文件夹为"E:\\dir\\"则获取的名字为"dir" String dirName = srcFile.getName(); //目标文件夹的完整路径 String destDirPath = destDir + File.separator + dirName + File.separator; File destDirFile = new File(destDirPath); if(destDirFile.getAbsolutePath().equals(srcFile.getAbsolutePath())) { return false; } if(destDirFile.exists() && destDirFile.isDirectory() && !overwriteExistDir) { // 目标位置有一个同名文件夹且不允许覆盖同名文件夹,则直接返回false return false; } if(!destDirFile.exists() && !destDirFile.mkdirs()) { // 如果目标目录不存在并且创建目录失败 return false; } File[] fileList = srcFile.listFiles(); //获取源文件夹下的子文件和子文件夹 if(fileList.length==0) { // 如果源文件夹为空目录则直接设置flag为true,这一步非常隐蔽,debug了很久 flag = true; } else { for(File temp: fileList) { if(temp.isFile()) { // 文件 flag = copyFile(temp.getAbsolutePath(), destDirPath, overwriteExistDir); // 递归复制时也继承覆盖属性 } else if(temp.isDirectory()) { // 文件夹 flag = copyDirectory(temp.getAbsolutePath(), destDirPath, overwriteExistDir); // 递归复制时也继承覆盖属性 } if(!flag) { break; } } } return flag; } /** * 删除文件或文件夹 * @param path * 待删除的文件的绝对路径 * @return boolean */ public static boolean deleteFile(String path) { boolean flag = false; File file = new File(path); if (!file.exists()) { // 文件不存在直接返回 return flag; } flag = file.delete(); return flag; } /** * 由上面方法延伸出剪切方法:复制+删除 * @param destDir 同上 */ public static boolean cutGeneralFile(String srcPath, String destDir) { boolean flag = false; if(copyGeneralFile(srcPath, destDir) && deleteFile(srcPath)) { // 复制和删除都成功 flag = true; } return flag; } public static void main(String[] args) { /** 测试复制文件 */ System.out.println(copyGeneralFile("d://test/test.html", "d://test/test/")); // 一般正常场景 System.out.println(copyGeneralFile("d://notexistfile", "d://test/")); // 复制不存在的文件或文件夹 System.out.println(copyGeneralFile("d://test/test.html", "d://test/")); // 待复制文件与目标文件在同一目录下 System.out.println(copyGeneralFile("d://test/test.html", "d://test/test/")); // 覆盖目标目录下的同名文件 System.out.println(copyFile("d://test/", "d://test2", false)); // 不覆盖目标目录下的同名文件 System.out.println(copyGeneralFile("d://test/test.html", "notexist://noexistdir/")); // 复制文件到一个不可能存在也不可能创建的目录下 System.out.println("---------"); /** 测试复制文件夹 */ System.out.println(copyGeneralFile("d://test/", "d://test2/")); System.out.println("---------"); /** 测试删除文件 */ System.out.println(deleteFile("d://a/")); } }
更多java实现文件复制、剪切文件和删除示例相关文章请关注PHP中文网!

핫 AI 도구

Undresser.AI Undress
사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover
사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool
무료로 이미지를 벗다

Clothoff.io
AI 옷 제거제

Video Face Swap
완전히 무료인 AI 얼굴 교환 도구를 사용하여 모든 비디오의 얼굴을 쉽게 바꾸세요!

인기 기사

뜨거운 도구

메모장++7.3.1
사용하기 쉬운 무료 코드 편집기

SublimeText3 중국어 버전
중국어 버전, 사용하기 매우 쉽습니다.

스튜디오 13.0.1 보내기
강력한 PHP 통합 개발 환경

드림위버 CS6
시각적 웹 개발 도구

SublimeText3 Mac 버전
신 수준의 코드 편집 소프트웨어(SublimeText3)

뜨거운 주제











시스템 도킹의 필드 매핑 처리 시스템 도킹을 수행 할 때 어려운 문제가 발생합니다. 시스템의 인터페이스 필드를 효과적으로 매핑하는 방법 ...

데이터베이스 작업에 MyBatis-Plus 또는 기타 ORM 프레임 워크를 사용하는 경우 엔티티 클래스의 속성 이름을 기반으로 쿼리 조건을 구성해야합니다. 매번 수동으로 ...

다른 아키텍처 CPU에 대한 Java 프로그램의 메모리 누출 현상 분석. 이 기사는 Java 프로그램이 ARM과 X86 Architecture CPU에 다른 메모리 동작을 보여주는 사례에 대해 논의합니다.

IntellijideAultimate 버전을 사용하여 봄을 시작하십시오 ...

그룹 내에서 정렬을 구현하기 위해 이름을 숫자로 변환하는 방법은 무엇입니까? 그룹으로 사용자를 정렬 할 때는 종종 사용자 이름을 숫자로 변환하여 다르게 만들 수 있습니다 ...

일부 애플리케이션이 제대로 작동하지 않는 회사의 보안 소프트웨어에 대한 문제 해결 및 솔루션. 많은 회사들이 내부 네트워크 보안을 보장하기 위해 보안 소프트웨어를 배포 할 것입니다. ...

Java 객체 및 배열의 변환 : 캐스트 유형 변환의 위험과 올바른 방법에 대한 심층적 인 논의 많은 Java 초보자가 객체를 배열로 변환 할 것입니다 ...

Java 원격 디버깅의 지속적인 획득에 대한 질문과 답변 원격 디버깅에 Java를 사용할 때 많은 개발자가 어려운 현상을 만날 수 있습니다. 그것...
