<rt id="bn8ez"></rt>
<label id="bn8ez"></label>

  • <span id="bn8ez"></span>

    <label id="bn8ez"><meter id="bn8ez"></meter></label>

    我的java天地

    java復(fù)制文件或文件夾

    @import url(http://www.tkk7.com/CuteSoft_Client/CuteEditor/Load.ashx?type=style&file=SyntaxHighlighter.css);@import url(/css/cuteeditor.css);
    package com.xuanwu.mtoserver.util;

    import java.io.*;

    /**
     * 
    @author Toby 復(fù)制文件夾或文件夾
     
    */
    public class FileUtil {

        
    public static void main(String args[]) throws IOException {
            
    // 源文件夾
            String url1 = "D:/user/test/";
            
    // 目標(biāo)文件夾
            String url2 = "D:/user/testcopy/";
            
    // 創(chuàng)建目標(biāo)文件夾
            (new File(url2)).mkdirs();
            
    // 獲取源文件夾當(dāng)前下的文件或目錄
            File[] file = (new File(url1)).listFiles();
            
    for (int i = 0; i < file.length; i++) {
                
    if (file[i].isFile()) {
                    
    // 復(fù)制文件
                    String type = file[i].getName().substring(file[i].getName().lastIndexOf("."+ 1);

                    
    if (type.equalsIgnoreCase("txt"))// 轉(zhuǎn)碼處理
                        copyFile(file[i], new File(url2 + file[i].getName()), MTOServerConstants.CODE_UTF_8, MTOServerConstants.CODE_GBK);
                    
    else
                        copyFile(file[i], 
    new File(url2 + file[i].getName()));
                }
                
    if (file[i].isDirectory()) {
                    
    // 復(fù)制目錄
                    String sourceDir = url1 + File.separator + file[i].getName();
                    String targetDir 
    = url2 + File.separator + file[i].getName();
                    copyDirectiory(sourceDir, targetDir);
                }
            }
        }

        
    // 復(fù)制文件
        public static void copyFile(File sourceFile, File targetFile) throws IOException {
            BufferedInputStream inBuff 
    = null;
            BufferedOutputStream outBuff 
    = null;
            
    try {
                
    // 新建文件輸入流并對它進(jìn)行緩沖
                inBuff = new BufferedInputStream(new FileInputStream(sourceFile));

                
    // 新建文件輸出流并對它進(jìn)行緩沖
                outBuff = new BufferedOutputStream(new FileOutputStream(targetFile));

                
    // 緩沖數(shù)組
                byte[] b = new byte[1024 * 5];
                
    int len;
                
    while ((len = inBuff.read(b)) != -1) {
                    outBuff.write(b, 
    0, len);
                }
                
    // 刷新此緩沖的輸出流
                outBuff.flush();
            } 
    finally {
                
    // 關(guān)閉流
                if (inBuff != null)
                    inBuff.close();
                
    if (outBuff != null)
                    outBuff.close();
            }
        }

        
    // 復(fù)制文件夾
        public static void copyDirectiory(String sourceDir, String targetDir) throws IOException {
            
    // 新建目標(biāo)目錄
            (new File(targetDir)).mkdirs();
            
    // 獲取源文件夾當(dāng)前下的文件或目錄
            File[] file = (new File(sourceDir)).listFiles();
            
    for (int i = 0; i < file.length; i++) {
                
    if (file[i].isFile()) {
                    
    // 源文件
                    File sourceFile = file[i];
                    
    // 目標(biāo)文件
                    File targetFile = new File(new File(targetDir).getAbsolutePath() + File.separator + file[i].getName());
                    copyFile(sourceFile, targetFile);
                }
                
    if (file[i].isDirectory()) {
                    
    // 準(zhǔn)備復(fù)制的源文件夾
                    String dir1 = sourceDir + "/" + file[i].getName();
                    
    // 準(zhǔn)備復(fù)制的目標(biāo)文件夾
                    String dir2 = targetDir + "/" + file[i].getName();
                    copyDirectiory(dir1, dir2);
                }
            }
        }

        
    /**
         * 
         * 
    @param srcFileName
         * 
    @param destFileName
         * 
    @param srcCoding
         * 
    @param destCoding
         * 
    @throws IOException
         
    */
        
    public static void copyFile(File srcFileName, File destFileName, String srcCoding, String destCoding) throws IOException {// 把文件轉(zhuǎn)換為GBK文件
            BufferedReader br = null;
            BufferedWriter bw 
    = null;
            
    try {
                br 
    = new BufferedReader(new InputStreamReader(new FileInputStream(srcFileName), srcCoding));
                bw 
    = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(destFileName), destCoding));
                
    char[] cbuf = new char[1024 * 5];
                
    int len = cbuf.length;
                
    int off = 0;
                
    int ret = 0;
                
    while ((ret = br.read(cbuf, off, len)) > 0) {
                    off 
    += ret;
                    len 
    -= ret;
                }
                bw.write(cbuf, 
    0, off);
                bw.flush();
            } 
    finally {
                
    if (br != null)
                    br.close();
                
    if (bw != null)
                    bw.close();
            }
        }

        
    /**
         * 
         * 
    @param filepath
         * 
    @throws IOException
         
    */
        
    public static void del(String filepath) throws IOException {
            File f 
    = new File(filepath);// 定義文件路徑
            if (f.exists() && f.isDirectory()) {// 判斷是文件還是目錄
                if (f.listFiles().length == 0) {// 若目錄下沒有文件則直接刪除
                    f.delete();
                } 
    else {// 若有則把文件放進(jìn)數(shù)組,并判斷是否有下級目錄
                    File delFile[] = f.listFiles();
                    
    int i = f.listFiles().length;
                    
    for (int j = 0; j < i; j++) {
                        
    if (delFile[j].isDirectory()) {
                            del(delFile[j].getAbsolutePath());
    // 遞歸調(diào)用del方法并取得子目錄路徑
                        }
                        delFile[j].delete();
    // 刪除文件
                    }
                }
            }
        }
    }




    package com.xuanwu.mtoserver.util;

    import java.io.File;
    import java.io.FileInputStream;
    import java.io.FileNotFoundException;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.OutputStream;
    import java.text.SimpleDateFormat;
    import java.util.ArrayList;
    import java.util.Iterator;
    import java.util.List;

    import org.apache.tools.ant.Project;
    import org.apache.tools.ant.taskdefs.Zip;
    import org.apache.tools.ant.types.FileSet;
    import org.dom4j.Document;
    import org.dom4j.DocumentHelper;
    import org.dom4j.Element;

    import com.xuanwu.smap.comapi.SmapMtMessage;

    import sun.misc.BASE64Decoder;
    import sun.misc.BASE64Encoder;

    /**
     * 
    @author Toby 通用工具類
     
    */
    public class Utils {

        
    /**
         * 
    @param args
         * 
    @throws Exception
         * 
    @throws IOException
         
    */
        
    public static void main(String[] args) throws IOException, Exception {
            
    // TODO Auto-generated method stub
            
    // File file = new File("D:/user/mms.xml");
            
    // System.out.println(file.renameTo(new File("D:/user/mms5.xml")));

            
    // 1
            
    // compress("D:/user/test", "D:/user/test.zip");

            
    /*
             * String fileName = "D:/user/88.zip"; try {
             * System.out.println(encryptBASE64(readFileToBytes(fileName))); } catch
             * (Exception e) { // TODO Auto-generated catch block
             * e.printStackTrace(); }
             
    */

            
    /*
             * String mi
             * ="UEsDBBQACAA";
             * RandomAccessFile inOut = new RandomAccessFile(
             * "D:/user/sample.","rw"); inOut.write(decryptBASE64(mi));
             * inOut.close();
             
    */

            
    // System.out.println(new String(decryptBASE64("5rWL6K+V"),"utf-8"));
            
    // 2
            
    // String xml =
            
    // createXML("1828","qww","123456","10658103619033","15918542546",encryptBASE64("兩款茶飲潤肺護(hù)膚防過敏".getBytes()),encryptBASE64(readFileToBytes("D:/user/test.zip")));
            
    // System.out.println(xml);
            /*
             * String xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"
             * standalone=\"yes\"?><TaskDataTransfer4ERsp
             * xmlns=\"
    http://www.aspirehld.com/iecp/TaskDataTransfer4ERsp\"><ResultCode>2000</ResultCode><TaskId></TaskId><ResultMSG>沒有獲得IP鑒權(quán)!</ResultMSG></TaskDataTransfer4ERsp>";
             * 
             * Document doc = DocumentHelper.parseText(xml); // 將字符串轉(zhuǎn)為XML Element
             * rootElt = doc.getRootElement(); // 獲取根節(jié)點(diǎn)
             * 
             * String resultCode = rootElt.element("ResultCode").getTextTrim();
             * String TaskId = rootElt.element("TaskId").getTextTrim(); String
             * ResultMSG = rootElt.element("ResultMSG").getTextTrim();
             * System.out.println(" "+resultCode+" "+TaskId+" "+ResultMSG);
             
    */

        }

        
    /**
         * BASE64解密
         * 
         * 
    @param key
         * 
    @return
         * 
    @throws Exception
         
    */
        
    public static byte[] decryptBASE64(String key) throws Exception {
            
    return (new BASE64Decoder()).decodeBuffer(key);
        }

        
    /**
         * BASE64加密
         * 
         * 
    @param key
         * 
    @return
         * 
    @throws Exception
         
    */
        
    public static String encryptBASE64(byte[] key) throws Exception {
            
    return (new BASE64Encoder()).encodeBuffer(key);
        }

        
    /**
         * 獲取路徑下所有文件名
         * 
         * 
    @param path
         * 
    @return
         
    */
        
    public static String[] getFile(String path) {
            File file 
    = new File(path);
            String[] name 
    = file.list();
            
    return name;
        }

        
    /**
         * 
         * 
    @param sourceDirPath
         * 
    @param targetDirPath
         * 
    @throws IOException
         
    */
        
    public static void copyDir(String sourceDirPath, String targetDirPath) throws IOException {
            
    // 創(chuàng)建目標(biāo)文件夾
            (new File(targetDirPath)).mkdirs();
            
    // 獲取源文件夾當(dāng)前下的文件或目錄
            File[] file = (new File(sourceDirPath)).listFiles();
            
    for (int i = 0; i < file.length; i++) {
                
    if (file[i].isFile()) {
                    
    // 復(fù)制文件
                    String type = file[i].getName().substring(file[i].getName().lastIndexOf("."+ 1);

                    
    if (type.equalsIgnoreCase("txt"))
                        FileUtil.copyFile(file[i], 
    new File(targetDirPath + file[i].getName()), MTOServerConstants.CODE_UTF_8,
                                MTOServerConstants.CODE_GBK);
                    
    else
                        FileUtil.copyFile(file[i], 
    new File(targetDirPath + file[i].getName()));
                }
                
    if (file[i].isDirectory()) {
                    
    // 復(fù)制目錄
                    String sourceDir = sourceDirPath + File.separator + file[i].getName();
                    String targetDir 
    = targetDirPath + File.separator + file[i].getName();
                    FileUtil.copyDirectiory(sourceDir, targetDir);
                }
            }
        }

        
    /**
         * 讀取文件中內(nèi)容
         * 
         * 
    @param path
         * 
    @return
         * 
    @throws IOException
         
    */
        
    public static String readFileToString(String path) throws IOException {
            String resultStr 
    = null;
            FileInputStream fis 
    = null;
            
    try {
                fis 
    = new FileInputStream(path);
                
    byte[] inBuf = new byte[2000];
                
    int len = inBuf.length;
                
    int off = 0;
                
    int ret = 0;
                
    while ((ret = fis.read(inBuf, off, len)) > 0) {
                    off 
    += ret;
                    len 
    -= ret;
                }
                resultStr 
    = new String(new String(inBuf, 0, off, MTOServerConstants.CODE_GBK).getBytes());
            } 
    finally {
                
    if (fis != null)
                    fis.close();
            }
            
    return resultStr;
        }

        
    /**
         * 文件轉(zhuǎn)成字節(jié)數(shù)組
         * 
         * 
    @param path
         * 
    @return
         * 
    @throws IOException
         
    */
        
    public static byte[] readFileToBytes(String path) throws IOException {
            
    byte[] b = null;
            InputStream is 
    = null;
            File f 
    = new File(path);
            
    try {
                is 
    = new FileInputStream(f);
                b 
    = new byte[(int) f.length()];
                is.read(b);
            } 
    finally {
                
    if (is != null)
                    is.close();
            }
            
    return b;
        }

        
    /**
         * 將byte寫入文件中
         * 
         * 
    @param fileByte
         * 
    @param filePath
         * 
    @throws IOException
         
    */
        
    public static void byteToFile(byte[] fileByte, String filePath) throws IOException {
            OutputStream os 
    = null;
            
    try {
                os 
    = new FileOutputStream(new File(filePath));
                os.write(fileByte);
                os.flush();
            } 
    finally {
                
    if (os != null)
                    os.close();
            }
        }

        
    /**
         * 將目錄文件打包成zip
         * 
         * 
    @param srcPathName
         * 
    @param zipFilePath
         * 
    @return 成功打包true 失敗false
         
    */
        
    public static boolean compress(String srcPathName, String zipFilePath) {
            
    if (strIsNull(srcPathName) || strIsNull(zipFilePath))
                
    return false;

            File zipFile 
    = new File(zipFilePath);
            File srcdir 
    = new File(srcPathName);
            
    if (!srcdir.exists())
                
    return false;
            Project prj 
    = new Project();
            Zip zip 
    = new Zip();
            zip.setProject(prj);
            zip.setDestFile(zipFile);
            FileSet fileSet 
    = new FileSet();
            fileSet.setProject(prj);
            fileSet.setDir(srcdir);
            zip.addFileset(fileSet);
            zip.execute();
            
    return zipFile.exists();
        }

        
    /**
         * 判空字串
         * 
         * 
    @param str
         * 
    @return 為空true
         
    */
        
    public static boolean strIsNull(String str) {
            
    return str == null || str.equals("");
        }

        
    /**
         * 折分?jǐn)?shù)組
         * 
         * 
    @param ary
         * 
    @param subSize
         * 
    @return
         
    */
        
    public static List<List<Object>> splitAry(Object[] ary, int subSize) {
            
    int count = ary.length % subSize == 0 ? ary.length / subSize : ary.length / subSize + 1;

            List
    <List<Object>> subAryList = new ArrayList<List<Object>>();

            
    for (int i = 0; i < count; i++) {
                
    int index = i * subSize;

                List
    <Object> list = new ArrayList<Object>();
                
    int j = 0;
                
    while (j < subSize && index < ary.length) {
                    list.add(ary[index
    ++]);
                    j
    ++;
                }

                subAryList.add(list);
            }

            
    return subAryList;
        }

        
    /**
         * 
    @param mobile
         * 
    @return
         
    */
        
    public static String ArrayToString(Object[] mobile) {
            String destId 
    = "";
            
    for (Object phone : mobile) {
                destId 
    += " " + (String) phone;
            }
            
    return destId.trim();
        }

    }

    posted on 2011-12-05 14:17 tobyxiong 閱讀(67973) 評論(16)  編輯  收藏 所屬分類: java

    評論

    # re: java復(fù)制文件或文件夾 2012-03-19 14:14 flower

    一點(diǎn)水平都沒有的代碼  回復(fù)  更多評論   

    # re: java復(fù)制文件或文件夾 2012-06-07 11:44 SBflower

    沒水平你自己去寫,看個(gè)毛!傻逼!@flower
      回復(fù)  更多評論   

    # re: java復(fù)制文件或文件夾 2012-07-20 18:26 ketty

    這段代碼對我來說非常受用,非常感謝~~~  回復(fù)  更多評論   

    # re: java復(fù)制文件或文件夾[未登錄] 2012-10-24 10:46 chen

    很不錯(cuò)  回復(fù)  更多評論   

    # re: java復(fù)制文件或文件夾 2012-12-12 10:23 fu

    MTOServerConstants 能不能解釋這個(gè)類  回復(fù)  更多評論   

    # re: java復(fù)制文件或文件夾 2013-02-13 11:59 是打發(fā)

    講解的非常詳細(xì) <a href="http://www.biyingbocai.com">利博亞洲</a>  回復(fù)  更多評論   

    # re: java復(fù)制文件或文件夾[未登錄] 2013-03-05 17:47 hello

    FileUtils  回復(fù)  更多評論   

    # re: java復(fù)制文件或文件夾 2013-05-11 12:12 czm

    那請拿出高水平的代碼來秀一下@flower
      回復(fù)  更多評論   

    # re: java復(fù)制文件或文件夾 2013-09-12 11:46 yjl

    挺好的東西,可以參考哦  回復(fù)  更多評論   

    # re: java復(fù)制文件或文件夾 2013-10-28 11:12

    挺好的啊  回復(fù)  更多評論   

    # re: java復(fù)制文件或文件夾 2013-11-05 10:20 jimgo

    想不到復(fù)制個(gè)文件也有這么多學(xué)問  回復(fù)  更多評論   

    # re: java復(fù)制文件或文件夾[未登錄] 2013-12-22 13:42 啊啊

    不錯(cuò)  回復(fù)  更多評論   

    # re: java復(fù)制文件或文件夾 2013-12-24 20:18 新西奈

    謝謝分享!學(xué)習(xí)了!真的很好?。?!  回復(fù)  更多評論   

    # re: java復(fù)制文件或文件夾[未登錄] 2014-01-06 11:30 andy

    我出現(xiàn)個(gè)問題:目標(biāo)文件夾沒有權(quán)限(拒絕訪問),怎么解決  回復(fù)  更多評論   

    # re: java復(fù)制文件或文件夾 2014-01-30 12:55 karas

    File file=new File(路徑+File.separator+file.getName());
    初始化路徑?jīng)]寫全.自己檢查一下  回復(fù)  更多評論   

    # 采用遞歸調(diào)用可以簡化程序 2015-06-08 23:50 joren

    package Study.IoStream.Senior;

    import java.io.File;
    import java.io.FileInputStream;
    import java.io.FileNotFoundException;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.OutputStream;

    public class CopyStreamDirOne {

    /**
    * 文件夾的拷貝
    * 1.如果是文件,直接復(fù)制
    * 2.如果是文件夾,直接創(chuàng)建
    * 3.遞歸查找子文件夾
    *
    * @param args
    */
    public static void main(String[] args) {
    //源文件夾
    String strPath="D:/DTLFolder/DriversBackup/file2";
    File strFile=new File(strPath);

    //目標(biāo)文件夾
    String destPath="D:/DTLFolder/DriversBackup/test";
    File destFile=new File(destPath);

    copyDict(strFile,destFile);
    }
    /**
    * 復(fù)制文件夾
    * @param str
    * @param dest
    */
    public static void copyDict(File str,File dest){
    //判斷文件第一個(gè)文件為文件夾還是文件
    if(str.isFile()){
    try {
    copyFile(str,dest);//將原文件復(fù)制給dest
    } catch (FileNotFoundException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    System.out.println("沒有該文件,請重新確認(rèn)");
    }
    catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    System.out.println("輸出異常,請確認(rèn)");
    }
    }else if(str.isDirectory()){
    //假如是文件夾
    dest=new File(dest,str.getName()); //復(fù)制到目標(biāo)文件夾里
    dest.mkdirs(); //創(chuàng)建文件夾
    for(File subStr:str.listFiles()){
    copyDict(subStr,dest);
    }

    }

    }
    /**
    * 復(fù)制文件
    * @throws FileNotFoundException,IOException
    */
    public static void copyFile(File str,File dest) throws FileNotFoundException,IOException{
    //在目標(biāo)文件中創(chuàng)建文件名
    dest=new File(dest,str.getName());
    dest.createNewFile(); //創(chuàng)建文件
    //選擇流
    InputStream inpStr=new FileInputStream(str);
    OutputStream outStr=new FileOutputStream(dest);

    byte[] cas=new byte[1024]; //數(shù)據(jù)流通過讀取存儲在硬盤上的字節(jié)碼,故采用字節(jié)類型,并指定一次讀取的個(gè)數(shù)
    int len=0; //用于標(biāo)識個(gè)數(shù)
    while(-1!=(len=inpStr.read(cas))){
    //-1標(biāo)識文件讀取結(jié)束
    outStr.write(cas, 0, len);
    }
    //寫完之后,要運(yùn)行flush強(qiáng)制執(zhí)行
    outStr.flush();

    //關(guān)閉數(shù)據(jù)流 反向
    outStr.close();
    inpStr.close();
    }

    }
      回復(fù)  更多評論   

    <2015年6月>
    31123456
    78910111213
    14151617181920
    21222324252627
    2829301234
    567891011

    導(dǎo)航

    統(tǒng)計(jì)

    常用鏈接

    留言簿(3)

    隨筆分類(144)

    隨筆檔案(157)

    相冊

    最新隨筆

    搜索

    積分與排名

    最新評論

    閱讀排行榜

    評論排行榜

    主站蜘蛛池模板: 久久精品国产亚洲av品善| 国产V片在线播放免费无码| 国产精品无码免费专区午夜| 午夜视频在线免费观看| 毛片免费在线视频| 久久久久亚洲精品无码网址| 亚洲高清中文字幕| 美女裸免费观看网站| 特级精品毛片免费观看| 日日AV拍夜夜添久久免费| 亚洲国产精品SSS在线观看AV| 亚洲最大黄色网址| 免费国产草莓视频在线观看黄| 99精品视频免费在线观看| 国产在线19禁免费观看国产| 亚洲高清在线视频| 久久精品亚洲日本波多野结衣| 久久久免费的精品| 午夜国产羞羞视频免费网站| 911精品国产亚洲日本美国韩国| 国产一区二区三区亚洲综合| 67194成手机免费观看| 亚洲成av人片天堂网老年人| 亚洲欧洲日产v特级毛片| www永久免费视频| 性感美女视频在线观看免费精品 | 亚洲精品人成在线观看| 羞羞的视频在线免费观看| 精品福利一区二区三区免费视频 | 亚洲日韩AV一区二区三区四区| 花蝴蝶免费视频在线观看高清版 | 日韩电影免费在线观看| 免费吃奶摸下激烈视频| 精品亚洲成A人无码成A在线观看| 免费a级毛片无码a∨免费软件| 五月天婷亚洲天综合网精品偷| 四虎成人免费观看在线网址| 久久久亚洲精品无码| 人人鲁免费播放视频人人香蕉| 成人免费无码大片a毛片软件| 亚洲黄色片在线观看|