天天看點

java複制、删除檔案,建立檔案夾

public final class FileUtils
{
    private static final int TEMP_DIR_ATTEMPTS = 10000;

    private FileUtils()
    {
    }

    // 判斷檔案是否問軟連結,軟連接配接的定義:https://www.runoob.com/linux/linux-comm-ln.html
    // linux中的軟連結類似于windows中的快捷方式,一個形象的例子:https://blog.csdn.net/weixin_44153121/article/details/85258047
    public static boolean isSymbolicLink(File file)
    {
        try {
            File canonicalFile = file.getCanonicalFile();
            File absoluteFile = file.getAbsoluteFile();
            File parentFile = file.getParentFile();
            return !canonicalFile.getName().equals(absoluteFile.getName()) ||
                    parentFile != null && !parentFile.getCanonicalPath().equals(canonicalFile.getParent());
        }
        catch (IOException e) {
            // error on the side of caution
            return true;
        }
    }

    public static ImmutableList<File> listFiles(File dir)
    {
        /**
         * list()方法是傳回某個目錄下的所有檔案和目錄的檔案名,傳回的是String數組
         *
         * listFiles()方法是傳回某個目錄下所有檔案和目錄的絕對路徑,傳回的是File數組
         *
         * 所謂的 immutable 對象是指對象的狀态不可變,不可修改,是以這樣的對象天生就具有線程安全性。
         * 由于 immutable 集合在建立時,就确定了元素的所有資訊,不需要考慮後續的擴充問題
         */
        File[] files = dir.listFiles();
        if (files == null) {
            return ImmutableList.of();
        }
        return ImmutableList.copyOf(files);
    }

    public static ImmutableList<File> listFiles(File dir, FilenameFilter filter)
    {
        File[] files = dir.listFiles(filter);
        if (files == null) {
            return ImmutableList.of();
        }
        return ImmutableList.copyOf(files);
    }

    // 建立臨時目錄
    public static File createTempDir(String prefix)
    {
        // System.getproperty(“java.io.tmpdir”)是擷取作業系統緩存的臨時目錄,不同作業系統的緩存臨時目錄不一樣,
        //
        //   在Windows的緩存目錄為:C:\Users\登入使用者~1\AppData\Local\Temp\
        //
        //   Linux:/tmp
        return createTempDir(new File(System.getProperty("java.io.tmpdir")), prefix);
    }

    public static File createTempDir(File parentDir, String prefix)
    {
        String baseName = "";
        if (prefix != null) {
            baseName += prefix + "-";
        }

        baseName += System.currentTimeMillis() + "-";
        // 多次嘗試,直到成功,一種樂觀的解決方案
        for (int counter = 0; counter < TEMP_DIR_ATTEMPTS; counter++) {
            File tempDir = new File(parentDir, baseName + counter);
            if (tempDir.mkdir()) {
                return tempDir;
            }
        }
        throw new IllegalStateException("Failed to create directory within "
                + TEMP_DIR_ATTEMPTS + " attempts (tried "
                + baseName + "0 to " + baseName + (TEMP_DIR_ATTEMPTS - 1) + ')');
    }

    public static boolean deleteDirectoryContents(File directory)
    {
        checkArgument(directory.isDirectory(), "Not a directory: %s", directory);

        // 不需要删除軟連結目錄下的内容
        if (isSymbolicLink(directory)) {
            return false;
        }

        boolean success = true;
        for (File file : listFiles(directory)) {
            // 遞歸删除,設定辨別為success
            success = deleteRecursively(file) && success;
        }
        return success;
    }

    public static boolean deleteRecursively(File file)
    {
        boolean success = true;
        if (file.isDirectory()) {
            success = deleteDirectoryContents(file);
        }

        return file.delete() && success;
    }

    public static boolean copyDirectoryContents(File src, File target)
    {
        checkArgument(src.isDirectory(), "Source dir is not a directory: %s", src);
        // 不需要複制軟連結的内容
        if (isSymbolicLink(src)) {
            return false;
        }

        target.mkdirs();
        checkArgument(target.isDirectory(), "Target dir is not a directory: %s", src);

        boolean success = true;
        for (File file : listFiles(src)) {
            // 遞歸複制
            success = copyRecursively(file, new File(target, file.getName())) && success;
        }
        return success;
    }

    public static boolean copyRecursively(File src, File target)
    {
        if (src.isDirectory()) {
            return copyDirectoryContents(src, target);
        }
        else {
            try {
                Files.copy(src, target);
                return true;
            }
            catch (IOException e) {
                return false;
            }
        }
    }

    // 建立檔案
    public static File newFile(String parent, String... paths)
    {
        requireNonNull(parent, "parent is null");
        requireNonNull(paths, "paths is null");

        return newFile(new File(parent), ImmutableList.copyOf(paths));
    }

    public static File newFile(File parent, String... paths)
    {
        requireNonNull(parent, "parent is null");
        requireNonNull(paths, "paths is null");

        return newFile(parent, ImmutableList.copyOf(paths));
    }

    public static File newFile(File parent, Iterable<String> paths)
    {
        requireNonNull(parent, "parent is null");
        requireNonNull(paths, "paths is null");

        File result = parent;
        for (String path : paths) {
            result = new File(result, path);
        }
        return result;
    }
}