com.eryansky.common.utils.io.FileUtils.java Source code

Java tutorial

Introduction

Here is the source code for com.eryansky.common.utils.io.FileUtils.java

Source

/**
 *  Copyright (c) 2012-2014 http://www.eryansky.com
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 */
package com.eryansky.common.utils.io;

import com.eryansky.common.exception.ServiceException;
import com.eryansky.common.utils.Identities;
import com.eryansky.common.utils.StringUtils;
import org.apache.commons.codec.binary.Base64;

import java.io.*;
import java.net.URLEncoder;

/**
 * .
 * @author     : &Eryan eryanwcp@gmail.com
 * @date       : 2013-1-19 ?4:41:56
 */
public class FileUtils extends org.apache.commons.io.FileUtils {

    /**
     * ???? ??,UUID??,??????
     * 
     * @param fileName
     *            ??+?
     * @return
     */
    public static String generateUUIDFileName(String fileName) {
        String uuid = Identities.uuid();
        String str = fileName;
        str = uuid + "." + str.substring(str.lastIndexOf(".") + 1);
        return str;
    }

    /**
     * ??
     * 
     * @param filePath
     *            
     * @return ??
     */
    public static String getFileName(String filePath) {
        filePath = filePath.replace("\\", "/");
        if (filePath.indexOf("/") != -1) {
            return filePath.substring(filePath.lastIndexOf("/") + 1);
        }
        return filePath;
    }

    /**
     * ?
     * 
     * @param src
     *            ?
     * @param dst
     *            
     */
    public static void copyFile(File src, File dst) {
        try {
            FileInputStream in = null;
            FileOutputStream out = null;
            try {
                out = new FileOutputStream(dst);
                in = new FileInputStream(src);
                byte[] buffer = new byte[1024];
                int len = 0;
                while ((len = in.read(buffer)) > 0) {
                    out.write(buffer, 0, len);
                }
            } catch (Exception e) {
                e.printStackTrace();
                String dstpath = dst.getAbsolutePath();
                if (dstpath.lastIndexOf("/") != -1) {
                    dstpath = dstpath.subSequence(0, dstpath.lastIndexOf("/")).toString();
                } else {
                    dstpath = dstpath.subSequence(0, dstpath.lastIndexOf("\\")).toString();
                }
                createDirectory(dstpath);
                copyFile(src, dst);
            } finally {
                if (null != in) {
                    in.close();
                }
                if (null != out) {
                    out.close();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * ??
     * 
     * @param Directorypath
     */
    public static void createDirectory(String Directorypath) {
        File file = new File(Directorypath);
        if (!file.exists()) {
            file.mkdir();
            file.mkdirs();
        }
    }

    /**
     * ??
     * 
     * @param dir
     */
    public static String checkSaveDir(String dir) {

        File dirFile = new File(dir);
        boolean flag = true;
        if (!dirFile.exists()) {
            flag = dirFile.mkdirs();
        }
        if (flag)
            return dirFile.getAbsolutePath();
        else
            return null;
    }

    /**
     * 
     * 
     * @param files
     */
    public static void deleteFile(File... files) {
        if (files == null) {
            return;
        }
        for (File f : files) {
            if (f.exists()) {
                f.delete();
            }
        }
    }

    /**
     * 
     * 
     * @param file
     */
    public static void deleteDirectory(File file) {
        if (file.exists()) { // ?
            if (file.isFile()) { // ?
                file.delete(); // delete() ? ??;
            } else if (file.isDirectory()) { // ?
                File[] files = file.listFiles(); //  files[];
                for (int i = 0; i < files.length; i++) { // ??
                    deleteDirectory(files[i]); // ? 
                }
            }
            file.delete();
        } else {
            System.out.println("??" + '\n');
        }
    }

    // ???
    public static String encodeDownloadFileName(String fileName, String agent) throws IOException {
        String codedfilename = null;
        if (agent != null) {
            agent = agent.toLowerCase();
        }
        if (null != agent && -1 != agent.indexOf("msie")) {
            String prefix = fileName.lastIndexOf(".") != -1 ? fileName.substring(0, fileName.lastIndexOf("."))
                    : fileName;
            String extension = fileName.lastIndexOf(".") != -1 ? fileName.substring(fileName.lastIndexOf(".")) : "";
            String name = prefix;
            int limit = 150 - extension.length();
            if (name.getBytes().length != name.length()) {// zn
                if (getEncodingByteLen(name) >= limit) {
                    name = subStr(name, limit);
                }
            } else {// en
                limit = prefix.length() > limit ? limit : prefix.length();
                name = name.substring(0, limit);
            }
            name = URLEncoder.encode(name + extension, "UTF-8").replace('+', ' ');
            codedfilename = name;
        } else if (null != agent && -1 != agent.indexOf("firefox")) {
            codedfilename = "=?UTF-8?B?" + (new String(Base64.encodeBase64(fileName.getBytes("UTF-8")))) + "?=";
        } else if (null != agent && -1 != agent.indexOf("safari")) {
            codedfilename = new String(fileName.getBytes("UTF-8"), "ISO8859-1");
        } else if (null != agent && -1 != agent.indexOf("applewebkit")) {
            codedfilename = new String(fileName.getBytes("UTF-8"), "ISO8859-1");
        } else {
            codedfilename = URLEncoder.encode(fileName, "UTF-8").replace('+', ' ');
        }
        return codedfilename;
    }

    private static int getEncodingByteLen(String sub) {
        int zhLen = (sub.getBytes().length - sub.length()) * 2;
        int enLen = sub.length() * 2 - sub.getBytes().length;
        return zhLen + enLen;
    }

    // ???
    private static String subStr(String str, int limit) {
        String result = str.substring(0, 17);
        int subLen = 17;
        for (int i = 0; i < limit; i++) {
            if (limit < getEncodingByteLen(
                    str.substring(0, (subLen + i) > str.length() ? str.length() : (subLen)))) {
                result = str.substring(0, subLen + i - 1);
                break;
            }
            if ((subLen + i) > str.length()) {
                result = str.substring(0, str.length() - 1);
                break;
            }
        }
        return result;
    }

    @SuppressWarnings("rawtypes")
    public static String getAppPath(Class cls) {
        // ??
        if (cls == null)
            throw new IllegalArgumentException("???");
        ClassLoader loader = cls.getClassLoader();
        // ????
        String clsName = cls.getName() + ".class";
        // ?
        Package pack = cls.getPackage();
        String path = "";
        // ?????
        if (pack != null) {
            String packName = pack.getName();
            // ??JavaJDK
            if (packName.startsWith("java.") || packName.startsWith("javax."))
                throw new IllegalArgumentException("????");
            // ??????
            clsName = clsName.substring(packName.length() + 1);
            // ?????????
            if (packName.indexOf(".") < 0)
                path = packName + "/";
            else {// ???????
                int start = 0, end = 0;
                end = packName.indexOf(".");
                while (end != -1) {
                    path = path + packName.substring(start, end) + "/";
                    start = end + 1;
                    end = packName.indexOf(".", start);
                }
                path = path + packName.substring(start) + "/";
            }
        }
        // ClassLoadergetResource????
        java.net.URL url = loader.getResource(path + clsName);
        // URL??
        String realPath = url.getPath();
        // ?????"file:"
        int pos = realPath.indexOf("file:");
        if (pos > -1)
            realPath = realPath.substring(pos + 5);
        // ????
        pos = realPath.indexOf(path + clsName);
        realPath = realPath.substring(0, pos - 1);
        // JARJAR??
        if (realPath.endsWith("!"))
            realPath = realPath.substring(0, realPath.lastIndexOf("/"));
        /*------------------------------------------------------------ 
         ClassLoadergetResourceutf-8?? 
          ??? 
          URLDecoderdecode? 
          ? 
        -------------------------------------------------------------*/
        try {
            realPath = java.net.URLDecoder.decode(realPath, "utf-8");
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        System.out.println("realPath----->" + realPath);
        return realPath;
    }

    /**
      * 
      * @param file
      * @return
      */
    public static String readFile(File file) {
        StringBuffer sb = new StringBuffer();
        BufferedReader br = null;
        try {
            br = new BufferedReader(new InputStreamReader(new FileInputStream(file)));
            String data = null;
            while ((data = br.readLine()) != null) {
                sb.append(data).append("\n");
            }
            br.close();
        } catch (FileNotFoundException e) {
            throw new ServiceException("?", e);
        } catch (IOException e) {
            throw new ServiceException("?IO", e);
        }
        return sb.toString();
    }

    /**
     * ?
     * @param file
     * @param charSet
     * @return
     */
    public static String readFile(File file, String charSet) {
        StringBuffer sb = new StringBuffer();
        BufferedReader br = null;
        try {
            br = new BufferedReader(new InputStreamReader(new FileInputStream(file), charSet));
            String data = null;
            while ((data = br.readLine()) != null) {
                sb.append(data).append("\n");
            }
            br.close();
        } catch (FileNotFoundException e) {
            throw new ServiceException("?", e);
        } catch (IOException e) {
            throw new ServiceException("?IO", e);
        }
        return sb.toString();
    }

    /**
     * ? \\  / ? File.separator
     * @param path
     * @return
     */
    public static String path(String path) {
        String p = StringUtils.replace(path, "\\", "/");
        p = StringUtils.join(StringUtils.split(p, "/"), "/");
        if (!StringUtils.startsWithAny(p, "/") && StringUtils.startsWithAny(path, "\\", "/")) {
            p += "/";
        }
        if (!StringUtils.endsWithAny(p, "/") && StringUtils.endsWithAny(path, "\\", "/")) {
            p = p + "/";
        }
        return p;
    }

}