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.
I guess you want to sum the total space
availableSpace += store.getUsableSpace() / (1024*1024);
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With