user1285928
user1285928

Reputation: 1476

Incorrect Linux free space

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.

Upvotes: 3

Views: 189

Answers (2)

Scary Wombat
Scary Wombat

Reputation: 44844

I guess you want to sum the total space

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

Upvotes: 3

davek
davek

Reputation: 22915

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.

Upvotes: 2

Related Questions