org.h819.commons.file.MyFileUtils.java Source code

Java tutorial

Introduction

Here is the source code for org.h819.commons.file.MyFileUtils.java

Source

package org.h819.commons.file;

import org.apache.commons.io.*;
import org.apache.commons.io.filefilter.NameFileFilter;
import org.apache.commons.io.filefilter.TrueFileFilter;
import org.apache.commons.lang3.SystemUtils;
import org.h819.commons.MyConstants;
import org.mozilla.universalchardet.UniversalDetector;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.nio.charset.Charset;
import java.nio.charset.IllegalCharsetNameException;
import java.nio.charset.StandardCharsets;
import java.nio.charset.UnsupportedCharsetException;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Collection;

/**
 * @author h819
 * @version V1.0  commons io ?? commons io???
 *          jdk 6  io ???
 * @ClassName: MyFileUtils
 * @Description: TODO()
 * @date May 14, 2009 10:15:24 AM
 */

// org.apache.commons.io.FilenameUtils ??separatorsToSystem 
// java.nio.file.Files ,java.nio.file.Paths ??
public class MyFileUtils {

    private static Logger logger = LoggerFactory.getLogger(MyFileUtils.class);

    private static ArrayList<String> fileNames = null;

    /**
     * ?????
     */
    public MyFileUtils() {

    }

    /**
     * Attempts to figure out the character set of the file using the excellent juniversalchardet library.
     * https://code.google.com/p/juniversalchardet/
     * that is the encoding detector library of Mozilla
     *
     * @param file
     * @return
     * @throws IOException
     */
    public static Charset getEncoding(File file) throws IOException {

        byte[] buf = new byte[4096];
        BufferedInputStream bufferedInputStream = new BufferedInputStream(new FileInputStream(file));
        final UniversalDetector universalDetector = new UniversalDetector(null);
        int numberOfBytesRead;
        while ((numberOfBytesRead = bufferedInputStream.read(buf)) > 0 && !universalDetector.isDone()) {
            universalDetector.handleData(buf, 0, numberOfBytesRead);
        }
        universalDetector.dataEnd();
        String encoding = universalDetector.getDetectedCharset();
        universalDetector.reset();
        bufferedInputStream.close();

        if (encoding != null) { //??? ISO_8859_1
            logger.debug("Detected encoding for {} is {}.", file.getAbsolutePath(), encoding);
            try {
                return Charset.forName(encoding);
            } catch (IllegalCharsetNameException err) {
                logger.debug("Invalid detected charset name '" + encoding + "': " + err);
                return StandardCharsets.ISO_8859_1;
            } catch (UnsupportedCharsetException err) {
                logger.error("Detected charset '" + encoding + "' not supported: " + err);
                return StandardCharsets.ISO_8859_1;
            }
        } else {
            logger.info("encodeing is null, will use 'ISO_8859_1'  : " + file.getAbsolutePath() + " , " + encoding);
            return StandardCharsets.ISO_8859_1;

        }

    }

    /**
     * ? classpath ? jar ?
     * jar  java 
     *
     * @param resourceName ? jar ??
     *                     ?
     *                     "/license.dat"  jar 
     *                     "/abc/license.dat"  jar /abc/ 
     * @return ???
     */
    public static File copyResourceFileFromJarLibToTmpDir(String resourceName) {
        // ??
        //  { "/license.dat", "/pdfdecrypt.exe", "/SkinMagic.dll" };
        // { "/STCAIYUN.TTF" };
        InputStream is = MyFileUtils.class.getResourceAsStream(resourceName);

        if (is == null) {
            logger.info(resourceName + " not exist in jar liberary.");
            return null;
        }
        //??
        // java_jar_source_temp ???
        String tempfilepath = SystemUtils.getJavaIoTmpDir() + File.separator + MyConstants.JarTempDir
                + File.separator + resourceName;

        File resourceFile = new File(tempfilepath);

        logger.info("resource copy to :" + tempfilepath);

        try {
            // ???
            FileUtils.copyInputStreamToFile(is, resourceFile);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            IOUtils.closeQuietly(is);
            return null;
        }

        IOUtils.closeQuietly(is);
        return resourceFile;
    }

    /**
     * Finds files within a given directory. All files found are filtered by an name filter.
     * (? FileUtils.listFiles ?)
     *
     * @param directory       the directory to search in
     * @param fileNames       file names to apply when finding files.
     * @param recursive       if true all subdirectories are searched as well
     * @param caseSensitivity how to handle case sensitivity, null means case-sensitive (IOCase.SENSITIVE ,  IOCase.INSENSITIVE)
     * @return
     */
    public static Collection<File> listFiles(File directory, String[] fileNames, boolean recursive,
            IOCase caseSensitivity) {

        if (recursive)
            return FileUtils.listFiles(directory, new NameFileFilter(fileNames, caseSensitivity),
                    TrueFileFilter.INSTANCE);
        else
            return FileUtils.listFiles(directory, new NameFileFilter(fileNames, caseSensitivity), null);

    }

    /**
     * ?,????
     * ?
     *
     * @param srcPdf
     * @param descDirectory
     */
    public static void copyFileToDirectory(File srcPdf, File descDirectory) {
        try {
            if (descDirectory != null && (!descDirectory.exists() || !descDirectory.isDirectory()))
                FileUtils.forceMkdir(descDirectory);
            FileUtils.copyFileToDirectory(srcPdf, descDirectory);
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    /**
     * ????????
     */
    private static void exampleReadLargeFile() {

        File theFile = new File("");
        LineIterator it = null;

        try {

            it = FileUtils.lineIterator(theFile, "UTF-8");
            while (it.hasNext()) {
                String line = it.nextLine();
                // do something with line
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            LineIterator.closeQuietly(it);
        }
    }

    /**
     * ??
     *
     * @param fileSize
     * @return
     */
    public static String getHumanReadableSize(long fileSize) {

        String[] units = new String[] { "B", "KB", "MB", "GB", "TB" };
        int unitIndex = (int) (Math.log10(fileSize) / 3);
        double unitValue = 1 << (unitIndex * 10);
        return new DecimalFormat("#,##0.#").format(fileSize / unitValue) + " " + units[unitIndex];

    }

    /**
     * ??
     * ?
     *
     * @param srcFile       ??
     * @param descDirectory ??
     * @param charset       ???? StandardCharsets.UTF_8
     */
    // ??utf-8 ??? asc ?
    // gb2312  utf-8 ??

    // ? "windows "????
    public static void convertEncoding(File srcFile, File descDirectory, Charset charset) {

        // ?
        String[] extension = { "java", "html", "htm", "php", "ini", "bat", "css", "txt", "js", "jsp", "xml", "sql",
                "properties" };
        if (!descDirectory.exists()) {
            descDirectory.mkdir();
        }

        if (srcFile.isFile()) {
            if (FilenameUtils.isExtension(srcFile.getName().toLowerCase(), extension)) {
                try {
                    String encodingSrc = MyFileUtils.getEncoding(srcFile).name();
                    // logger.info(encodingSrc);
                    InputStreamReader in = new InputStreamReader(new FileInputStream(srcFile), encodingSrc);
                    File f = new File(descDirectory + File.separator + srcFile.getName());
                    OutputStreamWriter out = new OutputStreamWriter(new FileOutputStream(f), charset.name());
                    IOUtils.copy(in, out);
                    IOUtils.closeQuietly(in);
                    IOUtils.closeQuietly(out);
                    // logger.info(MyFileUtils.getDetectedEncoding(f).name());
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        } else if (srcFile.isDirectory()) {

            File fs[] = srcFile.listFiles();
            for (File f : fs)
                convertEncoding(f, new File(descDirectory + File.separator + srcFile.getName()), charset);
        } else {
            logger.info("wrong file type :" + srcFile.getAbsolutePath());
        }

    }

}