java代码如何获取可用内存呢?

java-教程王 Java经验 发布时间:2022-03-11 11:03:10 阅读数:14923 1
下文笔者通过示例的方式讲述java代码获取可用内存的方法分享,如下所示:
实现思路:
   借助Runtime.getRuntime()类即可获取指定的信息
例:
package com.java265.other;
import java.io.File;
public class Test11 {
	/**
	 * java265.com 示例演示
	 */
	public static void main(String[] args) throws Exception {
		/* Total number of processors or cores available to the JVM */
		System.out.println("Available processors (cores): " + Runtime.getRuntime().availableProcessors());

		/* Total amount of free memory available to the JVM */
		System.out.println("Free memory (bytes): " + Runtime.getRuntime().freeMemory());

		/* This will return Long.MAX_VALUE if there is no preset limit */
		long maxMemory = Runtime.getRuntime().maxMemory();
		/* Maximum amount of memory the JVM will attempt to use */
		System.out.println("Maximum memory (bytes): " + (maxMemory == Long.MAX_VALUE ? "no limit" : maxMemory));

		/* Total memory currently in use by the JVM */
		System.out.println("Total memory (bytes): " + Runtime.getRuntime().totalMemory());

		/* Get a list of all filesystem roots on this system */
		File[] roots = File.listRoots();

		/* For each filesystem root, print some info */
		for (File root : roots) {
			System.out.println("File system root: " + root.getAbsolutePath());
			System.out.println("Total space (bytes): " + root.getTotalSpace());
			System.out.println("Free space (bytes): " + root.getFreeSpace());
			System.out.println("Usable space (bytes): " + root.getUsableSpace());
		}
	}
}
--------运行以上代码,将输出以下信息------
Available processors (cores): 8
Free memory (bytes): 264491200
Maximum memory (bytes): 4229955584
Total memory (bytes): 266338304
File system root: C:\
Total space (bytes): 161469165568
Free space (bytes): 29989670912
Usable space (bytes): 29989670912
File system root: D:\
Total space (bytes): 214748360704
Free space (bytes): 27861917696
Usable space (bytes): 27861917696
File system root: E:\
Total space (bytes): 128849014784
Free space (bytes): 109176647680
Usable space (bytes): 109176647680
版权声明

本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。

本文链接: https://www.Java265.com/JavaJingYan/202203/16469683112464.html

最近发表

热门文章

好文推荐

Java265.com

https://www.java265.com

站长统计|粤ICP备14097017号-3

Powered By Java265.com信息维护小组

使用手机扫描二维码

关注我们看更多资讯

java爱好者