Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Incorrect Linux free space

Tags:

java

memory

I want to get Linux free space and 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 get always this message:

* WARNING Hard Drive free space 0 Megabytes is too low! *

Can you help me to fix my code?

On Windows I don't see this warning message.

like image 744
user1285928 Avatar asked May 20 '26 14:05

user1285928


2 Answers

I guess you want to sum the total space

availableSpace += store.getUsableSpace() / (1024*1024);
like image 66
Scary Wombat Avatar answered May 23 '26 04:05

Scary Wombat


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

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

availableSpace is always re-assigned for each loop iteration. That may well be what you want (or not!), but you are implicitly hiding any file store information other than the last one.

like image 27
davek Avatar answered May 23 '26 03:05

davek