net.ymate.platform.commons.util.FileUtils.java Source code

Java tutorial

Introduction

Here is the source code for net.ymate.platform.commons.util.FileUtils.java

Source

/*
 * Copyright 2007-2107 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package net.ymate.platform.commons.util;

import java.io.File;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * <p>
 * FileUtils
 * </p>
 * <p>
 * ?
 * </p>
 * 
 * @author (suninformation@163.com)
 * @version 0.0.0
 *          <table style="border:1px solid gray;">
 *          <tr>
 *          <th width="100px">?</th><th width="100px"></th><th
 *          width="100px"></th><th width="100px"></th>
 *          </tr>
 *          <!--  Table ?? -->
 *          <tr>
 *          <td>0.0.0</td>
 *          <td></td>
 *          <td></td>
 *          <td>2010-4-23?01:14:10</td>
 *          </tr>
 *          </table>
 */
public class FileUtils {

    private static final Log _LOG = LogFactory.getLog(FileUtils.class);

    public static final Map<String, String> MIME_TYPE_MAPS = new HashMap<String, String>();

    static {
        Properties _configs = new Properties();
        InputStream _in = FileUtils.class.getClassLoader().getResourceAsStream("mimetypes-conf.properties");
        if (_in == null) {
            _in = FileUtils.class.getClassLoader()
                    .getResourceAsStream("META-INF/mimetypes-default-conf.properties");
        }
        if (_in != null) {
            try {
                _configs.load(_in);
                for (Object _key : _configs.keySet()) {
                    String[] _values = StringUtils.split(_configs.getProperty((String) _key, ""), "|");
                    for (String _value : _values) {
                        MIME_TYPE_MAPS.put(_value, (String) _key);
                    }
                }
            } catch (Exception e) {
            }
        }
    }

    /**
     * ??
     * 
     * @param path
     * @return 0-????0
     */
    public static long getLastModifiedTimestamp(String path) {
        long l = 0;
        File f = new File(path);
        if (f.exists()) {
            try {
                l = f.lastModified();
            } catch (SecurityException e) {
                l = 0;
            }
        }
        return l;
    }

    /**
     * ?????
     *
     * @param clazz 
     * @return ???
     */
    public static long getClassLastModifiedTimestamp(Class<?> clazz) {
        return getLastModifiedTimestamp(clazz.getResource(clazz.getSimpleName() + ".class").getFile());
    }

    /**
     * 
     * 
     * @param path ???
     * @param override ?true?false
     * @return
     */
    public static boolean mkdirs(String path, boolean override) {
        boolean _flag = false;
        File _path = new File(path);
        if (!_path.exists()) {
            _path.mkdirs();
            _flag = true;
        } else {
            if (override) {
                _flag = true;
            }
        }
        return _flag;
    }

    /**
     * ?
     * 
     * @param dir ?
     * @return 
     */
    public static String fixAndMkDir(String dir) {
        File _file = new File(dir);
        if (!_file.exists()) {
            _file.mkdirs();
        }
        return fixSeparator(_file.getPath());
    }

    /**
     * ?'\'?
     * 
     * @param dir ?
     * @return ??
     */
    public static String fixSeparator(String dir) {
        if (!dir.endsWith(File.separator)) {
            dir += File.separator;
        }
        return dir;
    }

    /**
     * @param filePath
     * @return ?????
     */
    public static String getNameFromPath(String filePath) {
        int i = filePath.lastIndexOf('/');
        if (i == -1) {
            return filePath;
        } else {
            return filePath.substring(i + 1);
        }
    }

    /**
     * @param fileName ??
     * @return ??????????
     */
    public static String getExtName(String fileName) {
        String suffix = "";
        int pos = fileName.lastIndexOf('.');
        if (pos > 0 && pos < fileName.length() - 1) {
            suffix = fileName.substring(pos + 1);
        }
        return suffix;
    }

    /**
     * @param url
     * @return URL???File, url?jarnull
     */
    public static File toFile(URL url) {
        if ((url == null) || (!url.getProtocol().equals("file"))) {
            return null;
        }
        String filename = url.getFile().replace('/', File.separatorChar);
        int pos = 0;
        while ((pos = filename.indexOf('%', pos)) >= 0) {
            if (pos + 2 < filename.length()) {
                String hexStr = filename.substring(pos + 1, pos + 3);
                char ch = (char) Integer.parseInt(hexStr, 16);
                filename = filename.substring(0, pos) + ch + filename.substring(pos + 3);
            }
        }
        return new File(filename);
    }

    /**
     * @param filePath
     * @return ??URL,?NULL, jarURL.toString()?filePath??"jar:"
     */
    public static URL toURL(String filePath) {
        if (StringUtils.isBlank(filePath)) {
            throw new IllegalArgumentException("Illegal argument 'filePath'!");
        }
        try {
            if (!filePath.startsWith("jar:") && !filePath.startsWith("file:") && !filePath.startsWith("zip:")
                    && !filePath.startsWith("http:") && !filePath.startsWith("ftp:")) {
                File _f = new File(filePath);
                return _f.toURI().toURL();
            }
            return new URL(filePath);
        } catch (MalformedURLException e) {
            _LOG.warn("", RuntimeUtils.unwrapThrow(e));
        }
        return null;
    }

}