Java实现文件夹的复制、移动、删除代码

来源:互联网 发布:if函数c语言 编辑:程序博客网 时间:2024/06/08 14:27
 

Java实现文件夹的复制、移动、删除代码
/** 
* @package cc.javaweb.documents 
* @File    MoveFile.java 
* */ 
package cc.javaweb.documents;  
 
import java.io.File;  
import java.io.FileInputStream;  
import java.io.FileOutputStream;  
import java.io.IOException;  
 
/** 
*


* Title:文件操作 
*


* desc: 提供文件移动、复制和删除的方法 
*


*/ 
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;  
    }  
 
    /** 
    * Java中文网:http://www.javaweb.cc 
    *  
    * @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();  
        }  
    }  
 
}

原创粉丝点击