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中文网!

Bytecodeachievesplatformincendence는 executedbirtualmachine (vm)을 beenecutedbyavirtmachine (vm)을 허용합니다

Java는 100% 플랫폼 독립성을 달성 할 수 없지만 플랫폼 독립성은 JVM 및 바이트 코드를 통해 구현되어 코드가 다른 플랫폼에서 실행되도록합니다. 특정 구현에는 다음이 포함됩니다. 1. 바이트 코드로의 컴파일; 2. JVM의 해석 및 실행; 3. 표준 라이브러리의 일관성. 그러나 JVM 구현 차이, 운영 체제 및 하드웨어 차이, 타사 라이브러리의 호환성은 플랫폼 독립성에 영향을 줄 수 있습니다.

Java는 "Writ 2. 유지 보수 비용이 낮 으면 하나의 수정 만 필요합니다. 3. 높은 팀 협업 효율성은 높고 지식 공유에 편리합니다.

새로운 플랫폼에서 JVM을 만드는 주요 과제에는 하드웨어 호환성, 운영 체제 호환성 및 성능 최적화가 포함됩니다. 1. 하드웨어 호환성 : JVM이 RISC-V와 같은 새로운 플랫폼의 프로세서 명령어 세트를 올바르게 사용할 수 있도록해야합니다. 2. 운영 체제 호환성 : JVM은 Linux와 같은 새로운 플랫폼의 시스템 API를 올바르게 호출해야합니다. 3. 성능 최적화 : 성능 테스트 및 튜닝이 필요하며 쓰레기 수집 전략은 새로운 플랫폼의 메모리 특성에 적응하도록 조정됩니다.

javafxeffecticallydressessplatforminconsistenciesinguedevelopment는 aplatform-agnosticscenegraphandcsstyling을 사용하여 development.1) itabstractsplatformspecificsthroughascenegraph, csstyling allowsforfine-tunin을 보장합니다

JVM은 Java 코드를 기계 코드로 변환하고 리소스를 관리하여 작동합니다. 1) 클래스로드 : .class 파일을 메모리에로드하십시오. 2) 런타임 데이터 영역 : 메모리 영역 관리. 3) 실행 엔진 : 해석 또는 컴파일 바이트 코드. 4) 로컬 메소드 인터페이스 : JNI를 통해 운영 체제와 상호 작용합니다.

JVM을 통해 Java는 플랫폼을 가로 질러 실행할 수 있습니다. 1) JVM 하중, 검증 및 바이트 코드를 실행합니다. 2) JVM의 작업에는 클래스 로딩, 바이트 코드 검증, 해석 실행 및 메모리 관리가 포함됩니다. 3) JVM은 동적 클래스 로딩 및 반사와 같은 고급 기능을 지원합니다.

Java 응용 프로그램은 다음 단계를 통해 다른 운영 체제에서 실행할 수 있습니다. 1) 파일 또는 경로 클래스를 사용하여 파일 경로를 처리합니다. 2) system.getenv ()를 통해 환경 변수를 설정하고 얻습니다. 3) Maven 또는 Gradle을 사용하여 종속성 및 테스트를 관리하십시오. Java의 크로스 플랫폼 기능은 JVM의 추상화 계층에 의존하지만 여전히 특정 운영 체제 별 기능의 수동 처리가 필요합니다.


핫 AI 도구

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

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

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

Clothoff.io
AI 옷 제거제

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

인기 기사

뜨거운 도구

Atom Editor Mac 버전 다운로드
가장 인기 있는 오픈 소스 편집기

에디트플러스 중국어 크랙 버전
작은 크기, 구문 강조, 코드 프롬프트 기능을 지원하지 않음

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

안전한 시험 브라우저
안전한 시험 브라우저는 온라인 시험을 안전하게 치르기 위한 보안 브라우저 환경입니다. 이 소프트웨어는 모든 컴퓨터를 안전한 워크스테이션으로 바꿔줍니다. 이는 모든 유틸리티에 대한 액세스를 제어하고 학생들이 승인되지 않은 리소스를 사용하는 것을 방지합니다.

Eclipse용 SAP NetWeaver 서버 어댑터
Eclipse를 SAP NetWeaver 애플리케이션 서버와 통합합니다.
