获取当前文件夹中的可用空间

时间:2014-03-30 17:10:14

标签: java nio java-8

我有这个Java代码,它获取HDD和RAM空间并检查可用空间。由于某些原因,它在Linux中无法正常工作。我每次都看到警告信息。如何获取当前文件夹的可用空间,我在运行Java代码?

import java.io.IOException;
import java.nio.file.FileStore;
import java.nio.file.FileSystem;
import java.nio.file.FileSystems;

public final class EnvironmentCheck{

    public EnvironmentCheck(){

        // If the HDD Free Space is less than 200 Megabytes write message HDD is too low
        if (200 > checkHDDFreeSpace()){
            System.out.println("*** WARNING Hard Drive free space " + checkHDDFreeSpace() + " Megabytes " + "is too low! ***");
            // TODO write the same messgae into the log file
        }

        // If the RAM Free Space is less than 200 Megabytes write message HDD is too low
        if (200 > checkRAMFreeSpace()){
            System.out.println("*** WARNING RAM free space " + checkRAMFreeSpace() + " Megabytes " + "is too low! ***");
            // TODO write the same messgae into the log file
        }

    }

    /**
    * Get available HDD Free space from the system
    *
    * @return
    */
    public long checkHDDFreeSpace(){

        long availableSpace = 0;

        FileSystem fs = FileSystems.getDefault();
        for (FileStore store : fs.getFileStores()){

            try{
                availableSpace = store.getUsableSpace() / 1024;
                //System.out.println(availableSpace);
            }catch (IOException e){

            }
        }
        return availableSpace;
    }

    /**
    * Get available RAM Free memory
    *
    * @return
    */
    public long checkRAMFreeSpace(){
        return Runtime.getRuntime().freeMemory();
    }

}

2 个答案:

答案 0 :(得分:2)

我想你想找出文件夹所在分区(mount mount)的可用空间。 您收到警告消息,因为您在每次迭代中覆盖avaialableSpace变量

for (FileStore store : fs.getFileStores()){
    try{
            //gets overwritten in each iteration, hence you get the
            //warning every time
            availableSpace = store.getUsableSpace() / 1024;
            //System.out.println(availableSpace);
        }catch (IOException e){

    }
}

首先尝试找到与您的目录对应的FileStore(例如,对于/usr/home/usr/home/foouser可以是{{1}},然后只获取该文件存储的大小

答案 1 :(得分:0)

我建议您首先尝试获取总可用内存,然后减去可用内存。

您可以尝试: -

for (FileStore store : fs.getFileStores()){
    try{
            long totalSpace=  store.getTotalSpace();
            long usableSpace=  store.getUsableSpace();
            availableSpace = (totalSpace - usableSpace) / 1024;
        }catch (IOException e){

    }
}

希望它会对你有所帮助。