FileUtils

来源:互联网 发布:人工智能专家系统 编辑:程序博客网 时间:2024/05/22 08:04
import org.apache.commons.io.IOUtils;import org.apache.commons.io.LineIterator;import org.apache.commons.io.filefilter.*;import java.io.*;import java.net.URL;import java.nio.channels.FileChannel;import java.util.ArrayList;import java.util.Collection;import java.util.Iterator;import java.util.List;import static org.apache.commons.io.FileUtils.forceDelete;import static org.apache.commons.io.FileUtils.isSymlink;public class FileUtils {    private static final long ONE_GB = 1024 * 1024 * 1024;    private static final long ONE_MB = 1024 * 1024;    private static final long ONE_KB = 1024;    private static final long FIFTY_MB = 50 * 1024 * 1024;    /***     * 获取系统的临时目录路径     */    public static String getTempDirectoryPath() {        return System.getProperty("java.io.tmpdir");    }    /***     * 获取代表系统临时目录的文件     */    public static File getTempDirectory() {        return new File(getTempDirectoryPath());    }    /***     * 获取用户的主目录路径     */    public static String getUserDirectoryPath() {        return System.getProperty("user.home");    }    /***     * 获取代表用户主目录的文件     */    public static File getUserDirectory() {        return new File(getUserDirectoryPath());    }    /***     * 根据指定的文件获取一个新的文件输入流     */    public static FileInputStream getInputStreamByFile(File file) throws IOException {        if (file.exists()) {            if (file.isDirectory()) {                throw new IOException("File '" + file + "' exists but is a directory");            }            if (!file.canRead()) {                throw new IOException("File '" + file + "' cannot be read");            }        } else {            throw new IOException("File '" + file + "' does not exist");        }        return new FileInputStream(file);    }    /***     * 根据指定的文件获取一个新的文件输出流     */    public static FileOutputStream getOutputStreamByFile(File file) throws IOException {        if (file.exists()) {            if (file.isDirectory()) {                throw new IOException("File'" + file + "' exists but is a directory");            }            if (!file.canWrite()) {                throw new IOException("File '" + file + "' cannot be written to");            }        } else {            File parent = file.getParentFile();            if (parent != null && !parent.exists()) {                if (!parent.mkdirs()) {                    throw new IOException("File '" + file + "' could not be created");                }            }        }        return new FileOutputStream(file);    }    /***     * 字节转换成直观带单位的值(包括单位GB,MB,KB或字节)     */    public static String byteCountToDisplaySize(long size) {        String displaySize;        if (size / ONE_GB > 0) {            displaySize = String.valueOf(size / ONE_GB) + " GB";        } else if (size / ONE_MB > 0) {            displaySize = String.valueOf(size / ONE_MB) + " MB";        } else if (size / ONE_KB > 0) {            displaySize = String.valueOf(size / ONE_KB) + " KB";        } else {            displaySize = String.valueOf(size) + " bytes";        }        return displaySize;    }    /***     * 创建一个空文件,若文件已经存在则只更改文件的最近修改时间     */    public static void touch(File file) throws IOException {        if (!file.exists()) {            OutputStream out = getOutputStreamByFile(file);            IOUtils.closeQuietly(out);        }        boolean success = file.setLastModified(System.currentTimeMillis());        if (!success) {            throw new IOException("Unableto set the last modification time for " + file);        }    }    /***     * 把相应的文件集合转换成文件数组     */    public static File[] convertFileCollectionToFileArray(Collection<File> files) {        return files.toArray(new File[files.size()]);    }    /***     * 根据一个过滤规则获取一个目录下的文件     */    private static void innerListFiles(Collection<File> files, File directory, IOFileFilter filter) {        File[] found = directory.listFiles((FileFilter) filter);        if (found != null) {            for (File file : found) {                if (file.isDirectory()) {                    innerListFiles(files, file, filter);                } else {                    files.add(file);                }            }        }    }    /***     * 根据一个IOFileFilter过滤规则获取一个目录下的文件集合listFiles     */    public static Collection<File> listFiles(File directory, IOFileFilter fileFilter, IOFileFilter dirFilter) {        if (!directory.isDirectory()) {            throw new IllegalArgumentException("Parameter'directory' is not a directory");        }        if (fileFilter == null) {            throw new NullPointerException("Parameter 'fileFilter' is null");        }        IOFileFilter effFileFilter = FileFilterUtils.and(fileFilter, FileFilterUtils.notFileFilter(DirectoryFileFilter.INSTANCE));        IOFileFilter effDirFilter;        if (dirFilter == null) {            effDirFilter = FalseFileFilter.INSTANCE;        } else {            effDirFilter = FileFilterUtils.and(dirFilter, DirectoryFileFilter.INSTANCE);        }        Collection<File> files = new java.util.LinkedList<File>();        innerListFiles(files, directory, FileFilterUtils.or(effFileFilter, effDirFilter));        return files;    }    /***     * 根据一个IOFileFilter过滤规则获取一个目录下的文件集合的Iterator迭代器iterateFiles     */    public static Iterator<File> iterateFiles(File directory, IOFileFilter fileFilter, IOFileFilter dirFilter) {        return listFiles(directory, fileFilter, dirFilter).iterator();    }    /***     * 把指定的字符串数组变成后缀名格式字符串数组     */    private static String[] toSuffixes(String[] extensions) {        String[] suffixes = new String[extensions.length];        for (int i = 0; i < extensions.length; i++) {            suffixes[i] = "." + extensions[i];        }        return suffixes;    }    /***     * 查找一个目录下面符合对应扩展名的文件的集合     */    public static Collection<File> listFiles(File directory, String[] extensions, boolean recursive) {        IOFileFilter filter;        if (extensions == null) {            filter = TrueFileFilter.INSTANCE;        } else {            String[] suffixes = toSuffixes(extensions);            filter = new SuffixFileFilter(suffixes);        }        return listFiles(directory, filter, (recursive ? TrueFileFilter.INSTANCE : FalseFileFilter.INSTANCE));    }    /***     * 查找一个目录下面符合对应扩展名的文件的集合的迭代器     */    public static Iterator<File> iterateFiles(File directory, String[] extensions, boolean recursive) {        return listFiles(directory, extensions, recursive).iterator();    }    /***     * 判断两个文件是否相等     */    public static boolean isFileContentEquals(File file1, File file2) throws IOException {        boolean file1Exists = file1.exists();        if (file1Exists != file2.exists()) {            return false;        }        if (!file1Exists) {            return true;        }        if (file1.isDirectory() || file2.isDirectory()) {            throw new IOException("Can't compare directories, only files");        }        if (file1.length() != file2.length()) {            return false;        }        if (file1.getCanonicalFile().equals(file2.getCanonicalFile())) {            return true;        }        InputStream input1 = null;        InputStream input2 = null;        try {            input1 = new FileInputStream(file1);            input2 = new FileInputStream(file2);            return IOUtils.contentEquals(input1, input2);        } finally {            IOUtils.closeQuietly(input1);            IOUtils.closeQuietly(input2);        }    }    /***     * 将一个文件数组转化成一个URL数组     */    public static URL[] toURLs(File[] files) throws IOException {        URL[] urls = new URL[files.length];        for (int i = 0; i < urls.length; i++) {            urls[i] = files[i].toURI().toURL();        }        return urls;    }    /***     * 拷贝一个文件到指定的目录文件     */    public static void copyFileToDirectory(File srcFile, File destDir) throws IOException {        copyFileToDirectory(srcFile, destDir, true);    }    /***     * 拷贝一个文件到指定的目录文件并且设置是否更新文件的最近修改时间     */    public static void copyFileToDirectory(File srcFile, File destDir, boolean preserveFileDate) throws IOException {        if (destDir == null) {            throw new NullPointerException("Destination must not be null");        }        if (destDir.exists() && !destDir.isDirectory()) {            throw new IllegalArgumentException("Destination '" + destDir + "' is not adirectory");        }        File destFile = new File(destDir, srcFile.getName());        copyFile(srcFile, destFile, preserveFileDate);    }    /***     * 拷贝文件到新的文件中并且保存最近修改时间     */    public static void copyFile(File srcFile, File destFile) throws IOException {        copyFile(srcFile, destFile, true);    }    /***     * 拷贝文件到新的文件中并且设置是否保存最近修改时间     */    public static void copyFile(File srcFile, File destFile, boolean preserveFileDate) throws IOException {        if (srcFile == null) {            throw new NullPointerException("Source must not be null");        }        if (destFile == null) {            throw new NullPointerException("Destination must not be null");        }        if (!srcFile.exists()) {            throw new IOException("Source '" + srcFile + "' does not exist");        }        if (srcFile.isDirectory()) {            throw new IOException("Source '" + srcFile + "' exists but is a directory");        }        if (srcFile.getCanonicalPath().equals(destFile.getCanonicalPath())) {            throw new IOException("Source '" + srcFile + "' and destination '" + destFile + "' are the same");        }        if (destFile.getParentFile() != null && !destFile.getParentFile().exists()) {            if (!destFile.getParentFile().mkdirs()) {                throw new IOException("Destination '" + destFile + "' directory cannot becreated");            }        }        if (destFile.exists() && !destFile.canWrite()) {            throw new IOException("Destination '" + destFile + "' exists but is read-only");        }        doCopyFile(srcFile, destFile, preserveFileDate);    }    /***     * 拷贝文件到新的文件中并且设置是否保存最近修改时间     */    private static void doCopyFile(File srcFile, File destFile, boolean preserveFileDate) throws IOException {        if (destFile.exists() && destFile.isDirectory()) {            throw new IOException("Destination '" + destFile + "' exists but is a directory");        }        FileInputStream fis = null;        FileOutputStream fos = null;        FileChannel input = null;        FileChannel output = null;        try {            fis = new FileInputStream(srcFile);            fos = new FileOutputStream(destFile);            input = fis.getChannel();            output = fos.getChannel();            long size = input.size();            long pos = 0;            long count = 0;            while (pos < size) {                count = (size - pos) > FIFTY_MB ? FIFTY_MB : (size - pos);                pos += output.transferFrom(input, pos, count);            }        } finally {            IOUtils.closeQuietly(output);            IOUtils.closeQuietly(fos);            IOUtils.closeQuietly(input);            IOUtils.closeQuietly(fis);        }        if (srcFile.length() != destFile.length()) {            throw new IOException("Failed to copy full contents from '" + srcFile + "' to '" + destFile + "'");        }        if (preserveFileDate) {            destFile.setLastModified(srcFile.lastModified());        }    }    /***     * 将一个目录拷贝到另一目录中,并且保存最近更新时间     */    public static void copyDirectoryToDirectory(File srcDir, File destDir) throws IOException {        if (srcDir == null) {            throw new NullPointerException("Source must not be null");        }        if (srcDir.exists() && !srcDir.isDirectory()) {            throw new IllegalArgumentException("Source'" + destDir + "' is not a directory");        }        if (destDir == null) {            throw new NullPointerException("Destination must not be null");        }        if (destDir.exists() && !destDir.isDirectory()) {            throw new IllegalArgumentException("Destination '" + destDir + "' is not a directory");        }        copyDirectory(srcDir, new File(destDir, srcDir.getName()), true);    }    /***     * 拷贝整个目录到新的位置,并且保存最近修改时间     */    public static void copyDirectory(File srcDir, File destDir) throws IOException {        copyDirectory(srcDir, destDir, true);    }    /***     * 拷贝整个目录到新的位置,并且设置是否保存最近修改时间     */    public static void copyDirectory(File srcDir, File destDir, boolean preserveFileDate) throws IOException {        copyDirectory(srcDir, destDir, null, preserveFileDate);    }    /***     * 拷贝过滤后的目录到指定的位置,并且保存最近修改时间     */    public static void copyDirectory(File srcDir, File destDir, FileFilter filter) throws IOException {        copyDirectory(srcDir, destDir, filter, true);    }    /***     * 拷贝过滤后的目录到指定的位置,并且设置是否保存最近修改时间     */    public static void copyDirectory(File srcDir, File destDir, FileFilter filter, boolean preserveFileDate) throws IOException {        if (srcDir == null) {            throw new NullPointerException("Source must not be null");        }        if (destDir == null) {            throw new NullPointerException("Destination must not be null");        }        if (!srcDir.exists()) {            throw new FileNotFoundException("Source '" + srcDir + "' does not exist");        }        if (!srcDir.isDirectory()) {            throw new IOException("Source '" + srcDir + "' exists but is not a directory");        }        if (srcDir.getCanonicalPath().equals(destDir.getCanonicalPath())) {            throw new IOException("Source '" + srcDir + "' and destination '" + destDir + "' are the same");        }        List<String> exclusionList = null;        if (destDir.getCanonicalPath().startsWith(srcDir.getCanonicalPath())) {            File[] srcFiles = filter == null ? srcDir.listFiles() : srcDir.listFiles(filter);            if (srcFiles != null && srcFiles.length > 0) {                exclusionList = new ArrayList<String>(srcFiles.length);                for (File srcFile : srcFiles) {                    File copiedFile = new File(destDir, srcFile.getName());                    exclusionList.add(copiedFile.getCanonicalPath());                }            }        }        doCopyDirectory(srcDir, destDir, filter, preserveFileDate, exclusionList);    }    /***     * 内部拷贝目录的方法     */    private static void doCopyDirectory(File srcDir, File destDir, FileFilter filter, boolean preserveFileDate, List<String> exclusionList) throws IOException {        File[] files = filter == null ? srcDir.listFiles() : srcDir.listFiles(filter);        if (files == null) {            throw new IOException("Failed to list contents of " + srcDir);        }        if (destDir.exists()) {            if (!destDir.isDirectory()) {                throw new IOException("Destination '" + destDir + "' exists but is not a directory");            }        } else {            if (!destDir.mkdirs()) {                throw new IOException("Destination '" + destDir + "' directory cannot be created");            }        }        if (!destDir.canWrite()) {            throw new IOException("Destination '" + destDir + "' cannot be written to");        }        for (File file : files) {            File copiedFile = new File(destDir, file.getName());            if (exclusionList == null || !exclusionList.contains(file.getCanonicalPath())) {                if (file.isDirectory()) {                    doCopyDirectory(file, copiedFile, filter, preserveFileDate, exclusionList);                } else {                    doCopyFile(file, copiedFile, preserveFileDate);                }            }        }        if (preserveFileDate) {            destDir.setLastModified(srcDir.lastModified());        }    }    /***     * 递归的删除一个目录     */    public static void deleteDirectory(File directory) throws IOException {        if (!directory.exists()) {            return;        }        if (!isSymlink(directory)) {            cleanDirectory(directory);        }        if (!directory.delete()) {            String message = "Unable to deletedirectory " + directory + ".";            throw new IOException(message);        }    }    /***     * 安静模式删除目录,操作过程中会抛出异常     */    public static boolean deleteQuietly(File file) {        if (file == null) {            return false;        }        try {            if (file.isDirectory()) {                cleanDirectory(file);            }        } catch (Exception ignored) {        }        try {            return file.delete();        } catch (Exception ignored) {            return false;        }    }    /***     * 清除一个目录而不删除它     */    public static void cleanDirectory(File directory) throws IOException {        if (!directory.exists()) {            String message = directory + " does not exist";            throw new IllegalArgumentException(message);        }        if (!directory.isDirectory()) {            String message = directory + " is not a directory";            throw new IllegalArgumentException(message);        }        File[] files = directory.listFiles();        if (files == null) {  // null if security restricted            throw new IOException("Failed to list contents of " + directory);        }        IOException exception = null;        for (File file : files) {            try {                forceDelete(file);            } catch (IOException ioe) {                exception = ioe;            }        }        if (null != exception) {            throw exception;        }    }    /***     * 把一个文件的内容读取到一个对应编码的字符串中去     */    public static String readFileToString(File file, String encoding) throws IOException {        InputStream in = null;        try {            in = getInputStreamByFile(file);            return IOUtils.toString(in, encoding);        } finally {            IOUtils.closeQuietly(in);        }    }    /***     * 读取文件的内容到虚拟机的默认编码字符串     */    public static String readFileToString(File file) throws IOException {        return readFileToString(file, null);    }    /***     * 把一个文件转换成字节数组返回     */    public static byte[] readFileToByteArray(File file) throws IOException {        InputStream in = null;        try {            in = getInputStreamByFile(file);            return IOUtils.toByteArray(in);        } finally {            IOUtils.closeQuietly(in);        }    }    /***     * 把文件中的内容逐行的拷贝到一个对应编码     */    public static List<String> readLines(File file, String encoding) throws IOException {        InputStream in = null;        try {            in = getInputStreamByFile(file);            return IOUtils.readLines(in, encoding);        } finally {            IOUtils.closeQuietly(in);        }    }    /***     * 把文件中的内容逐行的拷贝到一个虚拟机默认编码的     */    public static List<String> readLines(File file) throws IOException {        return readLines(file, null);    }    /***     * 根据对应编码返回对应文件内容的行迭代器     */    public static LineIterator lineIterator(File file, String encoding) throws IOException {        InputStream in = null;        try {            in = getInputStreamByFile(file);            return IOUtils.lineIterator(in, encoding);        } catch (IOException | RuntimeException ex) {            IOUtils.closeQuietly(in);            throw ex;        }    }    /***     * 根据虚拟机默认编码返回对应文件内容的行迭代器     */    public static LineIterator lineIterator(File file) throws IOException {        return lineIterator(file, null);    }    /***     * 根据对应编码把字符串写进对应的文件中     */    public static void writeStringToFile(File file, String data, String encoding) throws IOException {        OutputStream out = null;        try {            out = getOutputStreamByFile(file);            IOUtils.write(data, out, encoding);        } finally {            IOUtils.closeQuietly(out);        }    }    /***     * 根据虚拟机默认编码把字符串写进对应的文件中     */    public static void writeStringToFile(File file, String data) throws IOException {        writeStringToFile(file, data, null);    }}