Java to obtain current system memory and hard disk usage code

Source: Internet
Author: User
Tags disk usage

The code for Java to obtain current system memory is as follows:

/** *//**
 http://www.bt285.cn/ http://www.5a520.cn/
*/
import java.lang.management.ManagementFactory;
import com.sun.management.OperatingSystemMXBean;
public class OSTest {
    public static void main(String[] args)
    {
        OperatingSystemMXBean osmb = (OperatingSystemMXBean) ManagementFactory.getOperatingSystemMXBean();
        System.out.println("系统物理内存总计:" + osmb.getTotalPhysicalMemorySize() / 1024/1024 + "MB");
        System.out.println("系统物理可用内存总计:" + osmb.getFreePhysicalMemorySize() / 1024/1024 + "MB");    }
} 

Managementfactory.getoperatingsystemmxbean () returns the Operatingsystemmxbean inside the java.lang.management;

We want to use the Com.sun.management.OperatingSystemMXBean;

In the Java class Library, you can find:

Public abstract Interface Com.sun.management.OperatingSystemMXBean extends Java.lang.management.OperatingSystemMXBean

So we can force a conversion.

Hard disk use:

/** *//**
http://www.bt285.cn/ http://www.5a520.cn/
*/
import java.io.File;
/** *//**
 *
 * jdk6.0下的磁盘使用情况例子
 */ 
public class Diskfree {
    public static void main(String[] args) {
        File[] roots = File.listRoots();//获取磁盘分区列表  
        for (File file : roots) {
            System.out.println(file.getPath()+"信息如下:");
            System.out.println("空闲未使用 = " + file.getFreeSpace()/1024/1024/1024+"G");//空闲空间  
            System.out.println("已经使用 = " + file.getUsableSpace()/1024/1024/1024+"G");//可用空间  
            System.out.println("总容量 = " + file.getTotalSpace()/1024/1024/1024+"G");//总空间
            System.out.println();
        }
    }
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.