文件操作工具类

文件操作工具类

import org.apache.commons.lang3.StringUtils;
import org.apache.tools.ant.Project;
import org.apache.tools.ant.taskdefs.Zip;
import org.apache.tools.ant.types.FileSet;

import java.io.*;
import java.nio.channels.FileChannel;
import java.text.DateFormat;
import java.text.MessageFormat;
import java.util.*;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;


/**
 * 文件操作工具类
 * Created by 张勇波 on 2016/8/18.
 */
public class FileUtil {

    /**
     * 判断文件是否存在
     *
     * @param sFileName 文件路径
     * @return true - 存在、false - 不存在
     */
    public static boolean checkExist(String sFileName) {
        boolean result;
        try {
            File f = new File(sFileName);
            result = f.exists() && f.isFile();
        } catch (Exception e) {
            result = false;
        }
        return result;
    }

    /**
     * 创建目录
     *
     * @param dir 欲创建目录路径
     * @return 创建成功返回true,目录已存在或创建失败返回false
     */
    public static boolean createDirectory(String dir) {
        File f = new File(dir);
        if (!f.exists()) {
            f.mkdirs();
            return true;
        }
        return false;
    }

    /**
     * 创建文件
     * 文件存在则终止,如需要根据业务需求调用deleteFromName删除文件
     *
     * @param fileDirectoryAndName 路径
     * @param fileContent          内容
     */
    public static void createNewFile(String fileDirectoryAndName, String fileContent) {
        if (!checkExist(fileDirectoryAndName)) {
            //创建File对象,参数为String类型,表示目录名
            try {
                new File(fileDirectoryAndName).createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
            //下面把数据写入创建的文件
            if (fileContent != null && fileContent.length() > 0)
                write(fileContent, fileDirectoryAndName, true);
        }
    }

    /**
     * 保存信息到指定文件
     *
     * @param physicalPath 保存文件物理路径
     * @param inputStream  目标文件的输入流
     * @param isbool       false:文件覆盖,true:文件追加
     * @return 保存成功返回true,反之返回false
     */
    public static boolean saveFileByPhysicalDir(String physicalPath, InputStream inputStream, boolean isbool) {
        boolean flag = false;
        if (checkExist(physicalPath)) {
            try {
                OutputStream os = new FileOutputStream(physicalPath, isbool);
                int readBytes;
                byte buffer[] = new byte[8192];
                while ((readBytes = inputStream.read(buffer, 0, 8192)) != -1) {
                    os.write(buffer, 0, readBytes);
                }
                os.close();
                flag = true;
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return flag;
    }

    /**
     * 向文件添加信息
     *
     * @param tivoliMsg   要写入的信息
     * @param logFileName 目标文件
     * @param isbool      true 追加文件,false 覆盖文件
     */
    public static boolean write(String tivoliMsg, String logFileName, boolean isbool) {
        boolean flag = false;
        try {
            if (checkExist(logFileName)) {
                byte[] bMsg = tivoliMsg.getBytes("UTF-8");
                FileOutputStream fOut = new FileOutputStream(logFileName, isbool);
                fOut.write(bMsg);
                fOut.close();
                flag = true;
            } else {
                System.out.println("FileUtil.write:文件不存在。" + logFileName);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return flag;
    }

    /**
     * 日志写入
     * 例如:
     * 2016/01/08 17:46:42 : 001 : 这是一个日志输出。
     * 2016/01/08 17:46:55 : 001 : 这是一个日志输出。
     *
     * @param logFile       日志文件
     * @param batchId       处理编号
     * @param exceptionInfo 异常信息
     */
    public static void writeLog(String logFile, String batchId, String exceptionInfo) {
        DateFormat df = DateFormat.getDateTimeInstance(DateFormat.DEFAULT, DateFormat.DEFAULT, Locale.JAPANESE);
        Object args[] = {df.format(new Date()), batchId, exceptionInfo};
        String fmtMsg = MessageFormat.format("{0} : {1} : {2}", args);
        try {
            File logfile = new File(logFile);
            if (!logfile.exists()) {
                logfile.createNewFile();
            }
            FileWriter fw = new FileWriter(logFile, true);
            fw.write(fmtMsg);
            fw.write(System.getProperty("line.separator"));
            fw.flush();
            fw.close();
        } catch (Exception ignored) {
        }
    }

    /**
     * 读取文件
     *
     * @param realPath    目标文件
     * @param charsetName 目标文件编码(为null或空时程序自动检测文件编码)
     * @return 文件内容
     */
    public static String readTextFile(String realPath, String charsetName) {
        StringBuilder txt = new StringBuilder();
        if (checkExist(realPath)) {
            BufferedReader br = null;
            try {
                if (StringUtils.isBlank(charsetName)) {
                    charsetName = new BytesEncodingDetect().getFileEncoding(realPath);
                }
                br = new BufferedReader(new InputStreamReader(new FileInputStream(realPath), charsetName));
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
            String temp;
            try {
                if (br != null) {
                    while ((temp = br.readLine()) != null) {
                        txt.append(temp);
                    }
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                if (br != null) {
                    br.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return txt.toString();
    }

    /**
     * 判断文件编码
     *
     * @param path 文件路径
     * @return 编码
     */
    public static String resolveCode(String path) {
        InputStream inputStream = null;
        try {
            inputStream = new FileInputStream(path);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        byte[] head = new byte[3];
        try {
            inputStream.read(head);
        } catch (IOException e) {
            e.printStackTrace();
        }
        String code = "GB2312";  //或GBK
        if (head[0] == -1 && head[1] == -2)
            code = "UTF-16";
        else if (head[0] == -2 && head[1] == -1)
            code = "Unicode";
        else if (head[0] == -17 && head[1] == -69 && head[2] == -65)
            code = "UTF-8";
        try {
            inputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return code;
    }

    /**
     * 复制文件
     *
     * @param srcFile    源文件路径
     * @param targetFile 目标文件路径
     */
    public static void copyFile(String srcFile, String targetFile) {
        if (checkExist(srcFile)) {
            FileInputStream fi = null;
            FileOutputStream fo = null;
            FileChannel in = null;
            FileChannel out = null;
            try {
                fi = new FileInputStream(srcFile);
                fo = new FileOutputStream(targetFile);
                in = fi.getChannel();
                out = fo.getChannel();
                in.transferTo(0, in.size(), out);
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                try {
                    if (fi != null) {
                        fi.close();
                    }
                    if (in != null) {
                        in.close();
                    }
                    if (fo != null) {
                        fo.close();
                    }
                    if (out != null) {
                        out.close();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * 复制文件夹
     *
     * @param sourceDir String 源文件夹
     * @param destDir   String 目标路径
     */
    public static void copyDir(String sourceDir, String destDir) {
        File sourceFile = new File(sourceDir);
        String tempSource;
        String tempDest;
        String fileName;
        if (new File(destDir).getParentFile().isDirectory()) {
            new File(destDir).mkdirs();
        }
        File[] files = sourceFile.listFiles();
        if (files != null) {
            for (File file : files) {
                fileName = file.getName();
                tempSource = sourceDir + "/" + fileName;
                tempDest = destDir + "/" + fileName;
                if (file.isFile()) {
                    copyFile(tempSource, tempDest);
                } else {
                    copyDir(tempSource, tempDest);
                }
            }
        }
    }

    /**
     * 移动(重命名)文件
     *
     * @param srcFile    源文件路径
     * @param targetFile 目标文件路径
     */
    public static void renameFile(String srcFile, String targetFile) {
        copyFile(srcFile, targetFile);
        deleteFromName(srcFile);
    }

    /**
     * 得到文件大小
     *
     * @param sFileName 文件路径
     * @return 文件大小(单位byte),文件不存在返回0,异常返回-1
     */
    public static long getSize(String sFileName) {
        long lSize = -1;
        try {
            if (checkExist(sFileName)) {
                File f = new File(sFileName);
                if (f.canRead()) {
                    lSize = f.length();
                } else {
                    lSize = -1;
                }
            }
        } catch (Exception e) {
            lSize = -1;
        }
        return lSize;
    }

    /**
     * 删除文件
     *
     * @param sFileName 文件路径
     * @return 成功返回true,反之返回false
     */
    public static boolean deleteFromName(String sFileName) {
        boolean bReturn = true;
        if (checkExist(sFileName)) {
            File oFile = new File(sFileName);
            if (!oFile.delete())
                bReturn = false;
        }
        return bReturn;
    }

    /**
     * 删除指定目录及其中的所有内容。
     *
     * @param dir 要删除的目录
     * @return 删除成功时返回true,否则返回false。
     */
    public static boolean deleteDirectory(File dir) {
        if (!dir.exists()) {
            return false;
        }
        File[] entries = dir.listFiles();
        if (entries != null) {
            for (File entry : entries) {
                if (entry.isDirectory()) {
                    if (!deleteDirectory(entry)) {
                        return false;
                    }
                } else {
                    if (!entry.delete()) {
                        return false;
                    }
                }
            }
        }
        return dir.delete();
    }

    /**
     * 解压缩
     *
     * @param sToPath  解压后路径 (为null或空时解压到源压缩文件路径)
     * @param sZipFile 压缩文件路径
     */
    public static void unZip(String sToPath, String sZipFile) {
        if (null == sToPath || ("").equals(sToPath.trim())) {
            File objZipFile = new File(sZipFile);
            sToPath = objZipFile.getParent();
        }
        ZipFile zfile = null;
        try {
            zfile = new ZipFile(sZipFile);
        } catch (IOException e) {
            e.printStackTrace();
        }
        Enumeration<? extends ZipEntry> zList = zfile != null ? zfile.entries() : null;
        ZipEntry ze;
        byte[] buf = new byte[1024];
        while (zList != null && zList.hasMoreElements()) {
            ze = zList.nextElement();
            if (ze.isDirectory()) {
                continue;
            }
            OutputStream os = null;
            try {
                os = new BufferedOutputStream(new FileOutputStream(getRealFileName(sToPath, ze.getName())));
            } catch (Exception e) {
                e.printStackTrace();
            }
            InputStream is;
            try {
                is = new BufferedInputStream(zfile.getInputStream(ze));
                int readLen;
                while ((readLen = is.read(buf, 0, 1024)) != -1) {
                    if (os != null) {
                        os.write(buf, 0, readLen);
                    }
                }
                is.close();
                if (os != null) {
                    os.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        try {
            if (zfile != null) {
                zfile.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * getRealFileName
     *
     * @param baseDir     Root Directory
     * @param absFileName absolute Directory File Name
     * @return java.io.File     Return file
     */
    private static File getRealFileName(String baseDir, String absFileName) {
        File ret;
        ArrayList dirs = new ArrayList();
        StringTokenizer st = new StringTokenizer(absFileName, System.getProperty("file.separator"));
        while (st.hasMoreTokens()) {
            dirs.add(st.nextToken());
        }
        ret = new File(baseDir);
        if (dirs.size() > 1) {
            for (int i = 0; i < dirs.size() - 1; i++) {
                ret = new File(ret, (String) dirs.get(i));
            }
        }
        if (!ret.exists())
            ret.mkdirs();
        ret = new File(ret, (String) dirs.get(dirs.size() - 1));
        return ret;
    }

    /**
     * 压缩文件夹
     *
     * @param srcPathName 预压缩的文件夹
     * @param finalFile   压缩后的zip文件 (为null或“”时默认同预压缩目录)
     * @param strIncludes 包括哪些文件或文件夹 eg:zip.setIncludes("*.java");(没有时可为null)支持通配符匹配,多个子项时以逗号或空格分隔
     * @param strExcludes 排除哪些文件或文件夹 (没有时可为null)支持通配符匹配,多个子项时以逗号或空格分隔
     */
    public static void zip(String srcPathName, String finalFile, String strIncludes, String strExcludes) {
        File srcdir = new File(srcPathName);
        if (!srcdir.exists()) {
            throw new RuntimeException(srcPathName + "不存在!");
        }
        if (finalFile == null || "".equals(finalFile)) {
            finalFile = srcPathName + ".zip";
        }
        File zipFile = new File(finalFile);
        Project prj = new Project();
        Zip zip = new Zip();
        zip.setProject(prj);
        zip.setDestFile(zipFile);
        FileSet fileSet = new FileSet();
        fileSet.setProject(prj);
        fileSet.setDir(srcdir);
        if (strIncludes != null && !"".equals(strIncludes)) {
            fileSet.setIncludes(strIncludes); //包括哪些文件或文件夹 eg:zip.setIncludes("*.java");
        }
        if (strExcludes != null && !"".equals(strExcludes)) {
            fileSet.setExcludes(strExcludes); //排除哪些文件或文件夹
        }
        zip.addFileset(fileSet);
        zip.execute();
    }
}

 上一篇
数字转换中文 数字转换中文
数字转换中文import java.util.Arrays; import java.util.HashMap; import java.util.Map; /** * 数字转中文,最大为千亿 */ public class NumTo
2019-08-19
下一篇 
新浪微博第三方js网页登陆(OAuth2 新浪微博第三方js网页登陆(OAuth2
新浪微博第三方js网页登陆(OAuth2.0)<!-- Sina第三方登录JS导入 --> <script src="http://tjs.sjs.sinajs.cn/open/api/js/wb.js?appkey=33470
2019-08-19
  目录