Incorrect Linux free space

I want to get free space and Linux memory using Java.

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! ***");
        }

        // 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! ***");
        }
    }

    public long checkHDDFreeSpace()
    {
        long availableSpace = 0;

        FileSystem fs = FileSystems.getDefault();
        for (FileStore store : fs.getFileStores())
        {
            try
            {
                availableSpace = store.getUsableSpace() / (1024*1024);
            }
            catch (IOException e)
            {
            }
        }
        return availableSpace;
    }

    public long checkRAMFreeSpace()
    {
        Runtime rt = Runtime.getRuntime();
        long freeMem = rt.maxMemory() - (rt.totalMemory() - rt.freeMemory());
        return freeMem / (1024 * 1024);
    }
}

      

I always get this message:

* WARNING Free space on hard disk 0 Megabyte is too low! *

Can you help me fix my code?

On Windows, I don't see this warning message.

+3


source to share


2 answers


I think you want a sum

common space



availableSpace += store.getUsableSpace() / (1024*1024);

      

+3


source


It seems that you are only returning the value from the final file store:

availableSpace = store.getUsableSpace() / (1024*1024);

      



availableSpace is always redefined for each loop iteration. This may be what you want (or not!), But you are implicitly hiding information about the file storage other than the last one.

+2


source







All Articles