首页

关于logstash源码包中FsUtil系统工具类判断指定路径下有无自定大小剩余空间hasFreeSpace源码分析

标签:FsUtil,系统工具类,logstash,可用磁盘空间,磁盘余量     发布时间:2018-04-05   

一、前言

关于logstashlogstash-master.zip源码包中org.logstash.common.FsUtil文件系统工具类,提供了实现判断指定文件路径对于指定大小磁盘空间是否够用hasFreeSpace方法,具体参考源码说明。

二、源码说明

package org.logstash.common;@b@@b@import java.io.File;@b@import java.io.IOException;@b@import java.util.Arrays;@b@import java.util.HashSet;@b@import java.util.Set;@b@import org.apache.logging.log4j.LogManager;@b@import org.apache.logging.log4j.Logger;@b@@b@/**@b@ * File System Utility Methods.@b@ */@b@public final class FsUtil {@b@@b@    private FsUtil() {@b@    }@b@@b@    private static final boolean IS_WINDOWS = System.getProperty("os.name").startsWith("Windows");@b@    private static final Logger logger = LogManager.getLogger(FsUtil.class);@b@@b@    /**@b@     * Checks if the request number of bytes of free disk space are available under the given@b@     * path.@b@     * @param path Directory to check@b@     * @param size Bytes of free space requested@b@     * @return True iff the@b@     * @throws IOException on failure to determine free space for given path's partition@b@     */@b@    public static boolean hasFreeSpace(final String path, final long size)@b@        throws IOException@b@    {@b@        final Set<File> partitionRoots = new HashSet<>(Arrays.asList(File.listRoots()));@b@@b@        // crawl up file path until we find a root partition@b@        File location = new File(path).getCanonicalFile();@b@        while (!partitionRoots.contains(location)) {@b@            location = location.getParentFile();@b@            if (location == null) {@b@                throw new IllegalStateException(String.format("Unable to determine the partition that contains '%s'", path));@b@            }@b@        }@b@@b@        final long freeSpace = location.getFreeSpace();@b@@b@        if (freeSpace == 0L && IS_WINDOWS) {@b@            // On Windows, SUBST'ed drives report 0L from getFreeSpace().@b@            // The API doc says "The number of unallocated bytes on the partition or 0L if the abstract pathname does not name a partition."@b@            // There is no straightforward fix for this and it seems a fix is included in Java 9.@b@            // One alternative is to launch and parse a DIR command and look at the reported free space.@b@            // This is a temporary fix to get the CI tests going which relies on SUBST'ed drives to manage long paths.@b@            logger.warn("Cannot retrieve free space on " +  location.toString() +  ". This is probably a SUBST'ed drive.");@b@            return true;@b@        }@b@@b@        return location.getFreeSpace() >= size;@b@    }@b@}