java对文件新建,删除,复制,剪切,重命名

本文介绍了一个Java文件资源管理器的实现细节,包括文件和文件夹的创建、删除、复制及重命名等基本操作,并提供了完整的代码示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

这几天学习java,试着做文件资源管理器,整理了一些文件的操作。


import java.io.File;
import java.io.*; 
import java.io.IOException;  
  
public class OperateFile {  
     
	//创建文件
    public static boolean createFile(String destFileName) {  
        File file = new File(destFileName);  
        if(file.exists()) {  
            System.out.println("创建单个文件" + destFileName + "失败,目标文件已存在!");  
            return false;  
        }  
        if (destFileName.endsWith(File.separator)) {  
            System.out.println("创建单个文件" + destFileName + "失败,目标文件不能为目录!");  
            return false;  
        }  
        //判断目标文件所在的目录是否存在  
        if(!file.getParentFile().exists()) {  
            //如果目标文件所在的目录不存在,则创建父目录  
            System.out.println("目标文件所在目录不存在,准备创建它!");  
            if(!file.getParentFile().mkdirs()) {  
                System.out.println("创建目标文件所在目录失败!");  
                return false;  
            }  
        }  
        //创建目标文件  
        try {  
            if (file.createNewFile()) {  
                System.out.println("创建单个文件" + destFileName + "成功!");  
                return true;  
            } else {  
                System.out.println("创建单个文件" + destFileName + "失败!");  
                return false;  
            }  
        } catch (IOException e) {  
            e.printStackTrace();  
            System.out.println("创建单个文件" + destFileName + "失败!" + e.getMessage());  
            return false;  
        }  
    }  
     
     //创建文件夹
    public static boolean createDir(String destDirName) {  
        File dir = new File(destDirName);  
        if (dir.exists()) {  
            System.out.println("创建目录" + destDirName + "失败,目标目录已经存在");  
            return false;  
        }  
        if (!destDirName.endsWith(File.separator)) {  
            destDirName = destDirName + File.separator;  
        }  
        //创建目录  
        if (dir.mkdirs()) {  
            System.out.println("创建目录" + destDirName + "成功!");  
            return true;  
        } else {  
            System.out.println("创建目录" + destDirName + "失败!");  
            return false;  
        }  
    }  
     //创建临时文件
    public static String createTempFile(String prefix, String suffix, String dirName) {  
        File tempFile = null;  
        if (dirName == null) {  
            try{  
                //在默认文件夹下创建临时文件  
                tempFile = File.createTempFile(prefix, suffix);  
                //返回临时文件的路径  
                return tempFile.getCanonicalPath();  
            } catch (IOException e) {  
                e.printStackTrace();  
                System.out.println("创建临时文件失败!" + e.getMessage());  
                return null;  
            }  
        } else {  
            File dir = new File(dirName);  
            //如果临时文件所在目录不存在,首先创建  
            if (!dir.exists()) {  
                if (!CreateFile.createDir(dirName)) {  
                    System.out.println("创建临时文件失败,不能创建临时文件所在的目录!");  
                    return null;  
                }  
            }  
            try {  
                //在指定目录下创建临时文件  
                tempFile = File.createTempFile(prefix, suffix, dir);  
                return tempFile.getCanonicalPath();  
            } catch (IOException e) {  
                e.printStackTrace();  
                System.out.println("创建临时文件失败!" + e.getMessage());  
                return null;  
            }  
        }  
    } 
    //删除文件
    public static boolean deleteDir(File dir){
    	boolean success = true;
    	if(dir.isDirectory()){
    		String[] children = dir.list();
    		for(int i = 0; i< children.length; i++){
    			success = deleteDir(new File(dir, children[i]));
    			if(!success){
    				return false;
    			}
    		}
    		success = dir.delete();
    	}else{
    		success = dir.delete();  
    	}
    	
    	return success;
    }
    //复制文件
    public static void copyFile(File sourceFile,File targetFile) throws IOException{  
    	// 新建文件输入流并对它进行缓冲   
        FileInputStream input = new FileInputStream(sourceFile);  
        BufferedInputStream inBuff = new BufferedInputStream(input);  
  
        // 新建文件输出流并对它进行缓冲   
        FileOutputStream output = new FileOutputStream(targetFile);  
        BufferedOutputStream outBuff = new BufferedOutputStream(output);  
  
        // 缓冲数组   
        byte[] b = new byte[1024 * 5];  
        int len;  
        while ((len =inBuff.read(b)) != -1) {  
        	outBuff.write(b, 0, len);  
        }  
        // 刷新此缓冲的输出流   
        outBuff.flush();  
        //关闭流   
        inBuff.close();  
        outBuff.close();  
        output.close();  
        input.close();  
    }  
    
    // 复制文件夹   
    public static void copyDirectiory(String sourceDir, String targetDir) throws IOException {  
		// 新建目标目录   
		(new File(targetDir)).mkdirs();  
		// 获取源文件夹当前下的文件或目录   
		File[] file = (new File(sourceDir)).listFiles();  
		for (int i = 0; i < file.length; i++) {  
		    if (file[i].isFile()) {  
		        // 源文件   
		    	File sourceFile = file[i];  
		    	// 目标文件   
		    	File targetFile = new   
				File(new File(targetDir).getAbsolutePath() + File.separator + file[i].getName());  
		    	copyFile(sourceFile, targetFile);  
		     }  
		    if (file[i].isDirectory()) {  
			    // 准备复制的源文件夹   
				String dir1 = sourceDir + "/" + file[i].getName();  
				// 准备复制的目标文件夹   
				String dir2 = targetDir + "/" + file[i].getName();  
			    copyDirectiory(dir1, dir2);  
		    }  
		}  
	}
    
    //文件重命名 
     public static void renameFile(String path,String oldname,String newname){ 
         if(!oldname.equals(newname)){//新的文件名和以前文件名不同时,才有必要进行重命名 
             File oldfile=new File(path+"/"+oldname); 
             File newfile=new File(path+"/"+newname); 
             if(!oldfile.exists()){
                 return;//重命名文件不存在
             }
             if(newfile.exists())//若在该目录下已经有一个文件和新文件名相同,则不允许重命名 
                 System.out.println(newname+"已经存在!"); 
             else{ 
                 oldfile.renameTo(newfile); 
             } 
         }else{
             System.out.println("新文件名和旧文件名相同...");
         }
     }
     //剪切文件
     public static void changeDirectory(String filename,String oldpath,String newpath,boolean cover){
         if(!oldpath.equals(newpath)) {
             File oldfile = new File(oldpath+"/"+filename);
             File newfile = new File(newpath+"/"+filename);
             if(newfile.exists()){//若在待转移目录下,已经存在待转移文件
                 if(cover)//覆盖
                     oldfile.renameTo(newfile);
                 else
                     System.out.println("在新目录下已经存在:"+filename);
             }
             else{
                 oldfile.renameTo(newfile);
             }
         }       
     }
    public static void main(String[] args) throws IOException { 
    	//----------------------复制文件---------------------//
        // 源文件夹   
        String url1 = "f:/css";  
        // 目标文件夹   
        String url2 = "d:/tempPhotos";
    	 // 创建目标文件夹   
        (new File(url2)).mkdirs();  
        // 获取源文件夹当前下的文件或目录   
        File[] file = (new File(url1)).listFiles();  
        for (int i = 0; i < file.length; i++) {  
            if (file[i].isFile()) {  
                // 复制文件   
                copyFile(file[i], new File(url2 +"\\"+ file[i].getName()));  
            }  
            if (file[i].isDirectory()) {  
                // 复制目录   
                String sourceDir = url1 + File.separator + file[i].getName();  
                String targetDir = url2 + File.separator + file[i].getName();  
                copyDirectiory(sourceDir, targetDir);  
            }  
        }  
    }  
}


评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值