com.us.util.FileHelper.java Source code

Java tutorial

Introduction

Here is the source code for com.us.util.FileHelper.java

Source

/*
 * @(#)FileDirHelper.java 2011-9-20
 * ?us??  2008-2011, Inc. All rights reserved.
 * s.server. Use is subject to license terms.
 */

package com.us.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLDecoder;
import java.util.Enumeration;

import org.apache.commons.io.FileUtils;
import org.apache.commons.logging.Log;

import com.us.exception.UsMsgException;

/**
 * 
 * 
 * @author <a href="mailto:monlyu.hong@gmail.com">monlyu</a>
 * @version 0.5.3, 2011-9-20
 * @since JDK6.0
 */
public class FileHelper {

    static Log log = LogHelper.getLog();

    /**
     * ??
     * 
     * @param parent 
     * @param fileName ??
     * @return ?
     */
    public static File getFile(File parent, String fileName) {
        return new File(parent.getAbsolutePath() + File.separatorChar + fileName);
    }

    /**
     * 
     * 
     * @param parent 
     * @param childrenDirs ?
     * @param fileName ??
     * @return
     */
    public static File mkdirAndGetFile(File parent, String childrenDirs, String fileName) {
        return getFile(mkdirs(parent, childrenDirs), fileName);
    }

    public static File mkdirAndGetFile(String parent, String childrenDirs, String fileName) {
        return getFile(mkdirs(new File(parent), childrenDirs), fileName);
    }

    /**
     * ??
     * 
     * @param parent 
     * @param fileName ??
     * @return ?
     */
    public static File getFile(String parent, String fileName) {
        return new File(parent, fileName);
    }

    public static File getClassFile(String root, String className) {
        String path = className.replace(".", File.separatorChar + "");
        return getFile(root, path);
    }

    /**
     * ?InputStream
     * 
     * @param stream ?
     * 
     *            <pre>
     * 680M: 17610ms
     * 283M: 6245ms
     * 
     * </pre>
     * @return
     * @throws Exception
     */
    public static long readLength(InputStream stream) {
        try {
            return stream.available();
        } catch (IOException e) {
            return 0;
        }
    }

    /**
     * 
     * 
     * @param packName ??
     * @param fileName ??
     * @return
     */
    public static InputStream getFileInPackage(String packName, String fileName) {
        try {
            String packdir = packName.replace('.', '/');
            Enumeration<URL> dirs = Thread.currentThread().getContextClassLoader().getResources(packdir);
            while (dirs.hasMoreElements()) {
                URL url = dirs.nextElement();
                if (url.getProtocol().equals("file")) {
                    String filePath = URLDecoder.decode(url.getFile(), "UTF-8");
                    return new FileInputStream(filePath + "/" + fileName);
                } else if (url.getProtocol().equals("jar")) {
                    return FileHelper.class.getClassLoader()
                            .getResourceAsStream(packdir.concat("/").concat(fileName));
                }
            }
        } catch (IOException e) {
            throw UsMsgException.newInstance(String.format(":%s.%s", packName, fileName), e);
        }
        return null;
    }

    public static void main(String[] args) {
        // InputStream s = getFileInPackage("template.simple", "a.ftl");
        // System.out.println(s.toString());
        System.out.println(getFile(getFile("~"), "/Pictures/ss.jps"));

    }

    /**
     * ???<br/>
     * <ol>
     * <li>~ [?]</li>
     * <li>root: [Web]</li>
     * </ol>
     * 
     * @param path
     * @return
     */
    public static File getFile(String path) {
        if (path.startsWith("~")) {
            if (OSHelper.isMac()) {
                return new File(System.getenv().get("HOME") + path.substring(1));
            }
            return new File(System.getenv().get("USERPROFILE") + path.substring(1));
        }
        if (path.startsWith("classpath:")) {
            Class<?> clazz = new FileHelper().getClass();
            String uripath = clazz.getResource(".").getPath();
            String packepath = clazz.getPackage().getName().replace(".", "/").toString();
            return new File(uripath.replace("/" + packepath, "").substring(1) + path.substring(10));
        }
        return new File(path);
    }

    /**
     * ?
     * 
     * @param parent 
     * @param create ??
     * @return
     */
    public static File getYMDDir(String parent, boolean create) {
        return getYMDDir(new File(parent), create);
    }

    /**
     * ?
     * 
     * @param parent 
     * @param create ??
     * @return
     */
    public static File getYMDDir(File parent, boolean create) {
        File file = getFile(parent, DateUtil.format(DateUtil.now(), "/yyyy/MM/dd/"));
        if (create && !file.exists()) {
            file.mkdirs();
        }
        return file;
    }

    /**
     * ?/
     * 
     * @param source /
     * @param target /
     */
    public static void copy(File source, File target) {
        try {
            if (source.isDirectory() && target.isDirectory()) {
                FileUtils.copyDirectory(source, target);
            } else if (source.isFile() && target.isDirectory()) {
                FileUtils.copyFileToDirectory(source, target);
            } else if (source.isFile()) {
                FileUtils.copyFile(source, target);
            }
        } catch (IOException e) {
            log.error("?", e);
        }
    }

    /**
     * ???
     * 
     * @param name ??
     * @return
     */
    public static String randomName(String name) {
        int indexOfDot = name.lastIndexOf(".");
        String fileType = name.substring(indexOfDot == -1 ? 0 : indexOfDot);
        return RandomHelper.uuid() + fileType;
    }

    /**
     * 
     * 
     * @param parent 
     * @param child ?
     * @return
     */
    public static File mkdirs(File parent, String child) {
        File f = getFile(parent, child);
        if (!f.exists())
            f.mkdirs();
        return f;
    }
}