JAVA文件处理类

import java.io.*;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * Created by 韩小转 on 2015/11/9 0009.
 */
public class FileUtil {


    public static final String separator=File.separator;

    /**
     * 创建目录
     *
     * @param dir 目录
     */
    public static void mkdir(String dir) {
        try {
            String dirTemp = dir;
            File dirPath = new File(dirTemp);
            if (!dirPath.exists()) {
                dirPath.mkdir();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * 创建目录
     *
     * @param dir 目录
     */
    public static void mkdirs(String dir) {
        try {
            String dirTemp = dir;
            File dirPath = new File(dirTemp);
            if (!dirPath.exists()) {
                dirPath.mkdirs();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 新建文件
     *
     * @param fileName
     *            String 包含路径的文件名 如:E:\phsftp\src\123.txt
     * @param content
     *            String 文件内容
     *
     */
    public static void createNewFile(String fileName, String content) {
        try {
            String fileNameTemp = fileName;
            File filePath = new File(fileNameTemp);
            if (!filePath.exists()) {
                filePath.createNewFile();
            }
            FileWriter fw = new FileWriter(filePath);
            PrintWriter pw = new PrintWriter(fw);
            String strContent = content;
            pw.println(strContent);
            pw.flush();
            pw.close();
            fw.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    /**
     * 删除文件
     *
     * @param fileName 包含路径的文件名
     */
    public static void delFile(String fileName) {
        try {
            String filePath = fileName;
            java.io.File delFile = new java.io.File(filePath);
            if(delFile.exists())
            	delFile.delete();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * 删除文件夹
     *
     * @param folderPath  文件夹路径
     */
    public static void delFolder(String folderPath) {
        try {
            // 删除文件夹里面所有内容
            delAllFile(folderPath);
            String filePath = folderPath;
            java.io.File myFilePath = new java.io.File(filePath);
            // 删除空文件夹
            myFilePath.delete();
        } catch (Exception e) {
            //log.error("删除文件夹操作出错"+e.getMessage());
            e.printStackTrace();
        }
    }


    /**
     * 删除文件夹里面的所有文件
     *
     * @param path 文件夹路径
     */
    public static void delAllFile(String path) {
        File file = new File(path);
        if (!file.exists()) {
            return;
        }
        if (!file.isDirectory()) {
            return;
        }
        String[] childFiles = file.list();
        File temp = null;
        for (int i = 0; i < childFiles.length; i++) {
            //separator与系统有关的默认名称分隔符
            //在UNIX系统上,此字段的值为'/';在Microsoft Windows系统上,它为 '\'。
            if (path.endsWith(separator)) {
                temp = new File(path + childFiles[i]);
            } else {
                temp = new File(path + separator + childFiles[i]);
            }
            if (temp.isFile()) {
                temp.delete();
            }
            if (temp.isDirectory()) {
                delAllFile(path + separator + childFiles[i]);// 先删除文件夹里面的文件
                delFolder(path + separator + childFiles[i]);// 再删除空文件夹
            }
        }
    }
    
    /**
     * 获取文件夹内所有文件
     * 只获取一级文件
     * hjl
     * 2017年7月14日17:42:50
     * @param src
     * @return
     */
    public static List<File> getAllFile(String src){
    	 File file = new File(src);
         if (!file.exists()) {
             return null;
         }
         if (!file.isDirectory()) {
             return null;
         }
         String[] childFiles = file.list();
         File temp = null;
         List<File> list = new ArrayList<>();
         for (int i = 0; i < childFiles.length; i++) {
             if (src.endsWith(separator)) {
                 temp = new File(src + childFiles[i]);
             } else {
                 temp = new File(src + separator + childFiles[i]);
             }
             if (temp.isFile()) {
            	 list.add(temp);
             }
         }
         return list;
    }


    /**
     * 复制单个文件
     *
     * @param srcFile
     *            包含路径的源文件 如:E:/phsftp/src/abc.txt
     * @param dirDest
     *            目标文件目录;若文件目录不存在则自动创建  如:E:/phsftp/dest
     * @throws IOException
     */
    public static void copyFile(String srcFile, String dirDest) {
        try {
            FileInputStream in = new FileInputStream(srcFile);
            mkdirs(dirDest);
            FileOutputStream out = new FileOutputStream(dirDest+separator+new File(srcFile).getName());
            int len;
            byte buffer[] = new byte[1024];
            while ((len = in.read(buffer)) != -1) {
                out.write(buffer, 0, len);
            }
            out.flush();
            out.close();
            in.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 复制文件夹
     *
     * @param oldPath
     *            String 源文件夹路径 如:E:/phsftp/src
     * @param newPath
     *            String 目标文件夹路径 如:E:/phsftp/dest
     * @return boolean
     */
    public static void copyFolder(String oldPath, String newPath) {
        try {
            // 如果文件夹不存在 则新建文件夹
            mkdir(newPath);
            File file = new File(oldPath);
            String[] files = file.list();
            File temp = null;
            for (int i = 0; i < files.length; i++) {
                if (oldPath.endsWith(separator)) {
                    temp = new File(oldPath + files[i]);
                } else {
                    temp = new File(oldPath + separator + files[i]);
                }

                if (temp.isFile()) {
                    FileInputStream input = new FileInputStream(temp);
                    FileOutputStream output = new FileOutputStream(newPath
                            + separator+ (temp.getName()).toString());
                    byte[] buffer = new byte[1024 * 2];
                    int len;
                    while ((len = input.read(buffer)) != -1) {
                        output.write(buffer, 0, len);
                    }
                    output.flush();
                    output.close();
                    input.close();
                }
                if (temp.isDirectory()) {// 如果是子文件夹
                    copyFolder(oldPath + separator + files[i], newPath +separator + files[i]);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 移动文件到指定目录
     *
     * @param oldPath 包含路径的文件名 如:E:/phsftp/src/ljq.txt
     * @param newPath 目标文件目录 如:E:/phsftp/dest
     */
    public static void moveFile(String oldPath, String newPath) {
        copyFile(oldPath, newPath);
        delFile(oldPath);
    }

    /**
     * 移动文件到指定目录,不会删除文件夹
     *
     * @param oldPath 源文件目录  如:E:/phsftp/src
     * @param newPath 目标文件目录 如:E:/phsftp/dest
     */
    public static void moveFiles(String oldPath, String newPath) {
        copyFolder(oldPath, newPath);
        delAllFile(oldPath);
    }

    /**
     * 移动文件到指定目录,会删除文件夹
     *
     * @param oldPath 源文件目录  如:E:/phsftp/src
     * @param newPath 目标文件目录 如:E:/phsftp/dest
     */
    public static void moveFolder(String oldPath, String newPath) {
        copyFolder(oldPath, newPath);
        delFolder(oldPath);
    }

   /* *//**
     * 解压zip文件
     *
     * @param srcDir
     *            解压前存放的目录
     * @param destDir
     *            解压后存放的目录
     * @throws Exception
     *//*
    public static void jieYaZip(String srcDir, String destDir) throws Exception {
        int leng = 0;
        byte[] b = new byte[1024*2];
        *//** 获取zip格式的文件 **//*
        File[] zipFiles = new FileFilterByExtension("zip").getFiles(srcDir);
        if(zipFiles!=null && !"".equals(zipFiles)){
            for (int i = 0; i < zipFiles.length; i++) {
                File file = zipFiles[i];
                *//** 解压的输入流 * *//*
                ZipInputStream zis = new ZipInputStream(new FileInputStream(file));
                ZipEntry entry=null;
                while ((entry=zis.getNextEntry())!=null) {
                    File destFile =null;
                    if(destDir.endsWith(separator)){
                        destFile = new File(destDir + entry.getName());
                    }else {
                        destFile = new File(destDir + "/" + entry.getName());
                    }
                    *//** 把解压包中的文件拷贝到目标目录 * *//*
                    FileOutputStream fos = new FileOutputStream(destFile);
                    while ((leng = zis.read(b)) != -1) {
                        fos.write(b, 0, leng);
                    }
                    fos.close();
                }
                zis.close();
            }
        }
    }


    /**
     * 读取数据
     *
     * @param inSream
     * @param charsetName
     * @return
     * @throws Exception
     */
    public static String readData(InputStream inSream, String charsetName) throws Exception{
        ByteArrayOutputStream outStream = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int len = -1;
        while( (len = inSream.read(buffer)) != -1 ){
            outStream.write(buffer, 0, len);
        }
        byte[] data = outStream.toByteArray();
        outStream.close();
        inSream.close();
        return new String(data, charsetName);
    }

    /**
     * 一行一行读取文件,适合字符读取,若读取中文字符时会出现乱码
     *
     * @param path
     * @return
     * @throws Exception
     */
    public static Set<String> readFile(String path) throws Exception{
        Set<String> datas=new HashSet<String>();
        FileReader fr=new FileReader(path);
        BufferedReader br=new BufferedReader(fr);
        String line=null;
        while ((line=br.readLine())!=null) {
            datas.add(line);
        }
        br.close();
        fr.close();
        return datas;
    }

    /**
     * 获取文件大小
     * @param files
     * @return
     */
    public static long getAllFileSize(File[] files){
        if(files==null||files.length<=0){
            return 0;
        }
        long size=0;
        for(int i=0;i<files.length;i++){
            size=size+files[i].length();
        }
        return size;
    }
    /**
     * 获取文件大小
     * @param path
     * @return
     */
    @Deprecated
    public static long getAllFileSize(String path){
        File file=new File(path);
        return getDirSize(file);
    }

    /**
     * 获取文件/文件夹内 所有 大小
     * @param file
     * @return
     */
    public static long getDirSize(File file) {
        //判断文件是否存在
        if (file.exists()) {
            //如果是目录则递归计算其内容的总大小
            if (file.isDirectory()) {
                File[] children = file.listFiles();
                long size = 0;
                for (File f : children)
                    size += getDirSize(f);
                return size;
            } else {
                long size =  file.length();
                return size;
            }
        } else {
            //System.out.println("文件或者文件夹不存在,请检查路径是否正确!");
            return 0;
        }
    }
    
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值