文件操作(复制文件、复制整个目录下的文件等等)

package com.framework.common.util;

import java.io.BufferedReader;
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.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;

public class FileOperateUtil {

   
    /**
     * 复制单个文件
     * 
     * @param srcFileName
     *            待复制的文件名
     * @param descFileName
     *            目标文件名
     * @param overlay
     *            如果目标文件存在,是否覆盖
     * @return 如果复制成功返回true,否则返回false
     */ 
    public static boolean copyFile(String srcFileName, String destFileName, 
            boolean overlay) { 
        File srcFile = new File(srcFileName); 
 
        // 判断源文件是否存在 
        if (!srcFile.exists()) { 
            throw new RuntimeException("源文件:" + srcFileName + "不存在!");
        } else if (!srcFile.isFile()) { 
            throw new RuntimeException("复制文件失败,源文件:" + srcFileName + "不是一个文件!");
        } 
 
        // 判断目标文件是否存在 
        File destFile = new File(destFileName); 
        if (destFile.exists()) { 
            // 如果目标文件存在并允许覆盖 
            if (overlay) { 
                // 删除已经存在的目标文件,无论目标文件是目录还是单个文件 
                new File(destFileName).delete(); 
            } 
        } else { 
            // 如果目标文件所在目录不存在,则创建目录 
            if (!destFile.getParentFile().exists()) { 
                // 目标文件所在目录不存在 
                if (!destFile.getParentFile().mkdirs()) { 
                    // 复制文件失败:创建目标文件所在目录失败 
                    return false; 
                } 
            } 
        } 
 
        // 复制文件 
        int byteread = 0; // 读取的字节数 
        InputStream in = null; 
        OutputStream out = null; 
 
        try { 
            in = new FileInputStream(srcFile); 
            out = new FileOutputStream(destFile); 
            byte[] buffer = new byte[1024]; 
 
            while ((byteread = in.read(buffer)) != -1) { 
                out.write(buffer, 0, byteread); 
            } 
            return true; 
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            return false; 
        } catch (IOException e) { 
            e.printStackTrace();
            return false; 
        } finally { 
            try { 
                if (out != null) 
                    out.close(); 
                if (in != null) 
                    in.close(); 
            } catch (IOException e) { 
                e.printStackTrace(); 
            } 
        } 
    } 
   
   
   
    /**
     * 复制整个目录的内容
     * 
     * @param srcDirName
     *            待复制目录的目录名
     * @param destDirName
     *            目标目录名
     * @param overlay
     *            如果目标目录存在,是否覆盖
     * @return 如果复制成功返回true,否则返回false
     */ 
    public static boolean copyDirectory(String srcDirName, String destDirName, 
            boolean overlay) { 
        // 判断源目录是否存在 
        File srcDir = new File(srcDirName); 
        if (!srcDir.exists()) { 
            throw new RuntimeException("复制目录失败:源目录" + srcDirName + "不存在!");
        } else if (!srcDir.isDirectory()) { 
            throw new RuntimeException("复制目录失败:" + srcDirName + "不是目录!");
        } 
 
        // 如果目标目录名不是以文件分隔符结尾,则加上文件分隔符 
        if (!destDirName.endsWith(File.separator)) { 
            destDirName = destDirName + File.separator; 
        } 
        File destDir = new File(destDirName); 
        // 如果目标文件夹存在 
        if (destDir.exists()) { 
            // 如果允许覆盖则删除已存在的目标目录 
            if (overlay) { 
                new File(destDirName).delete(); 
            } 
        } else { 
            // 创建目的目录 
            if (!destDir.mkdirs()) { 
                return false; 
            } 
        } 
 
        boolean flag = true; 
        File[] files = srcDir.listFiles(); 
        for (int i = 0; i < files.length; i++) { 
            // 复制文件 
            if (files[i].isFile()) { 
                System.out.println("??:"+files[i].getAbsolutePath()+"         ==      "+destDirName + files[i].getName());
                flag = FileOperateUtil.copyFile(files[i].getAbsolutePath(), 
                        destDirName + files[i].getName(), overlay); 
                if (!flag) 
                    break; 
            } else if (files[i].isDirectory()) { 
                flag = FileOperateUtil.copyDirectory(files[i].getAbsolutePath(), 
                        destDirName + files[i].getName(), overlay); 
                if (!flag) 
                    break; 
            } 
        } 
        if (!flag) { 
            throw new RuntimeException("复制目录" + srcDirName + "至" + destDirName + "失败!");
        } else { 
            return true; 
        } 
    } 
   
   
    /**
     * 遍历文件夹中文件
     * 
     * @param filepath
     * @return 返回file[]数组
     */ 
    public static File[] getFileList(String filepath) { 
        File d = null; 
        File list[] = null; 
        // 建立当前目录中文件的File对象 
        try { 
            d = new File(filepath); 
            if (d.exists()) { 
                list = d.listFiles(); 
            } 
        } catch (Exception ex) { 
            ex.printStackTrace(); 
        } 
        return list; 
    }
   
   
    /**
     * 读取文本文件内容
     * 
     * @param filePathAndName
     *            带有完整绝对路径的文件名
     * @param encoding
     *            文本文件打开的编码方式
     * @return 返回文本文件的内容
     */ 
    public static String readTxt(String filePathAndName, String encoding) 
            throws IOException { 
        encoding = encoding.trim(); 
        StringBuffer str = new StringBuffer(""); 
        String st = ""; 
        try { 
            FileInputStream fs = new FileInputStream(filePathAndName); 
            InputStreamReader isr; 
            if (encoding.equals("")) { 
                isr = new InputStreamReader(fs); 
            } else { 
                isr = new InputStreamReader(fs, encoding); 
            } 
            BufferedReader br = new BufferedReader(isr); 
            try { 
                String data = ""; 
                while ((data = br.readLine()) != null) { 
                    str.append(data); 
                } 
            } catch (Exception e) { 
                str.append(e.toString()); 
            } 
            st = str.toString(); 
            if (st != null && st.length() > 1) 
                st = st.substring(0, st.length() - 1); 
        } catch (IOException es) { 
            st = ""; 
        } 
        return st; 
    } 
   
   
    /**
     * 有编码方式的文件创建
     * 
     * @param filePathAndName
     *            文本文件完整绝对路径及文件名
     * @param fileContent
     *            文本文件内容
     * @param encoding
     *            编码方式 例如 GBK 或者 UTF-8
     * @return
     */ 
    public static void createFile(String filePathAndName, String fileContent, 
            String encoding) { 
 
        try { 
            String filePath = filePathAndName; 
            filePath = filePath.toString(); 
            File myFilePath = new File(filePath); 
            if (!myFilePath.exists()) { 
                myFilePath.createNewFile(); 
            } 
            PrintWriter myFile = new PrintWriter(myFilePath, encoding); 
            String strContent = fileContent; 
            myFile.println(strContent); 
            myFile.close(); 
        } catch (Exception e) { 
            e.printStackTrace();
        } 
    } 
 
    /**
     * 删除文件
     * 
     * @param filePathAndName
     *            文本文件完整绝对路径及文件名
     * @return Boolean 成功删除返回true遭遇异常返回false
     */ 
    public static boolean delFile(String filePathAndName) { 
        boolean bea = false; 
        try { 
            String filePath = filePathAndName; 
            File myDelFile = new File(filePath); 
            if (myDelFile.exists()) { 
                myDelFile.delete(); 
                bea = true; 
            } else { 
                bea = false; 
            } 
        } catch (Exception e) { 
            e.printStackTrace();
        } 
        return bea; 
    } 
   
   
   
    /**
     * 遍历指定目录下的子目录
     *
     * make by renhui on 2012-12-15 下午10:48:38
     * @param parent
     * @return
     */
    public static List<File> getDirectories(String parent){
        List<File> files = new ArrayList<File>();
        File rootFile = new File(parent);
        for(File file :rootFile.listFiles()){
            if(file.isDirectory()){
                files.add(file);
            }
        }
        return files;
    }
    /**
     * 创建文件或目录
     *
     * make by renhui on 2012-12-15 下午10:49:15
     * @param dirName
     */
    public static void createDirectory(String path){
        File file = new File(path);
        if(!file.exists()){
            file.mkdirs();
        }
    }
    /**
     * 删除文件或目录
     * 
     * make by renhui on 2012-12-15 下午10:51:45
     * @param dirName
     */
    public static void deleteFileOrDirectory(String fileName,Boolean deleteSubfile){
        File file = new File(fileName);
        if(deleteSubfile && file.isDirectory()){
            for(File subfile:file.listFiles()){
                if(subfile.isDirectory()){
                    deleteFileOrDirectory(subfile.getAbsolutePath(),deleteSubfile);
                }
                file.delete();
            }
        }
        file.delete();
    }
    /**
     * 重命名文件或目录
     *
     * make by renhui on 2013-8-8 下午1:18:45
     * @param orgName
     * @param newName
     */
    public static void renameFileOrDirectory(String orgName,String newName){
        File file = new File(orgName);
        file.renameTo(new File(newName));
    }
   
   
    /**
     * 删除指定目录下文件以及文件夹
     * 如:c://d 以及删除d文件夹
     *
     * make by Administrator on 2013-12-17 上午11:43:20
     * @param directoryPath
     */
    public static  void deleteDirectory(File directoryPath){
        if(directoryPath.isDirectory()){
            File[] files = directoryPath.listFiles();
            for(File delFile:files){
                if(delFile.isDirectory()){
                    deleteDirectory(delFile);
                }else{
                    delFile.delete();
                }
            }
        }
        directoryPath.delete();
    }
   
   
   
    public static void main(String[] args) {
        try {
            //ZipUtils.upZipFile(new File("C://gupload//1.zip"),"C://gupload//1");
//            System.out.println(FileOperateUtil.copyDirectory("C:\\gupload\\1\\files", "C:\\gupload\\files\\", true));
//            System.out.println(FileOperateUtil.copyDirectory("C:\\gupload\\2\\files", "C:\\gupload\\files\\", true));
           
           
           
//            System.out.println(FileOperateUtil.copyFile("C:\\gupload\\1.txt", "C:\\gupload\\files\\dxh.txt", false));
           
           
//            System.out.println(FileOperateUtil.readTxt("C:\\gupload\\1.txt", "utf-8"));
//           
//            FileOperateUtil.createFile("C:\\gupload\\554.txt", "lao  w s是东西黑", "utf-8");
           
            //FileOperateUtil.delFile("C:\\gupload\\554.txt");
           
            FileOperateUtil.deleteDirectory(new File("C:\\gupload\\files"));
           
           
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值