java实现文件夹的复制、移动、删除

本文提供了Java中文件移动、复制和删除的基本方法实现。介绍了如何通过renameTo方法移动文件到另一个目录,利用FileInputStream和FileOutputStream进行文件复制,并给出了递归删除目录及所有文件的示例。

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

      日前编程时需要进行对文件的移动和删除等操作,故把方法贴出来以便记忆。

/**
* @package com.sinosoft.services.transmission
* @File    MoveFile.java
* */
package com.sinosoft.services.transmission;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

/**
* <p>
* Title:文件操作
* <p>
* desc: 提供文件移动、复制和删除的方法
* <p>
*/
public class MoveFile {

    /**
    * Moving a File to Another Directory
    * 
    * @param srcFile
    *            eg: c:\windows\abc.txt
    * @param destPath
    *            eg: c:\temp
    */
    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;
    }

    /**
    * Copy a File to Another Directory
    * 
    * @param srcfile
    *            eg: c:\windows\abc.txt
    * @param destfile
    *            eg: c:\temp\abc.txt
    */
    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、付费专栏及课程。

余额充值