java中实现对文件以及文件夹的删除、复制、修改

本文提供了一个Java程序示例,展示了如何实现文件的移动、复制及删除功能。通过具体的方法实现,包括移动文件到新目录、复制文件内容以及清空指定路径下的所有文件。

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

复制、移动、删除代码
package cc.javaweb.documents;   
  
import java.io.File;   
import java.io.FileInputStream;   
import java.io.FileOutputStream;   
import java.io.IOException;   

  /**移动文件*/

public class MoveFile {   
  
    public static boolean move(String srcFile, String destPath) {   
        // File (or directory) to be moved   
        File file = new File(srcFile);   
  
        // Destination directory   
        File dir = new File(destPath);   
  
        // Move file to new directory   
        boolean success = file.renameTo(new File(dir, file.getName()));   
  
        return success;   
    }   
  

/**复制文件*/
    public static void copyfile(String srcfile, String destfile)   
            throws IOException // 使用FileInputStream和FileOutStream   
    {   
        FileInputStream fi = new FileInputStream(srcfile);   
        FileOutputStream fo = new FileOutputStream(destfile);   
        byte data[] = new byte[fi.available()];   
        System.out.println(fi.available());   
        fi.read(data);   
        fo.write(data);   
        fi.close();   
        fo.close();   
    }   
       
    /**  
    * Delete all context in a filepath  
    *   
    * @param File  
    */  
    public static void delAll(File f) throws IOException {   
        if(!f.exists()){   
            System.out.println("指定目录不存在:"+f.getName());   
        }else{   
        boolean rslt=true;// 保存中间结果   
        // 若文件夹非空。枚举、递归删除里面内容   
        File subs[] = f.listFiles();   
        for (int i = 0; i <= subs.length - 1; i++) {   
            if (subs[i].isDirectory())   
            delAll(subs[i]);// 递归删除子文件夹内容   
            rslt = subs[i].delete();// 删除子文件夹   
        }   
        rslt = f.delete();//删除文件夹本身   
        }   
    }   
       
  
    public static void main(String[] args) {   
        String srcfile = "D:\\admin\\Distribute\\receive\\package.rar";   
        String destfile = "D:\\admin\\Distribute\\store\\package.rar";   
        String destpath = "D:\\admin\\Distribute\\store";   
        // move(srcfile, destpath);   
        try {   
            copyfile(srcfile, destfile);   
        } catch (IOException e) {   
            // TODO Auto-generated catch block   
            e.printStackTrace();   
        }   
    }   
  
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值