读书人

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

发布时间: 2012-12-21 12:03:50 作者: rapoo

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

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

/*** @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();        }    }} 

?

读书人网 >编程

热点推荐