java程序运行时有时需要与运行平台交互以获取运行平台的相应信息,而java提供了了两个系统相关类来进行程序与运行平台的交互,分别是System类和Runtime类。
System类
System类代表当前java运行的平台,程序不能创建System实例,但System类提供了一些类方法和类变量来支持程序与运行平台的交互获取当前操作系统信息的方法
public static Properties getProperties() // 获取当前系统的所有信息
public String getProperty(String key) // 获取当前系统某个指定的信息
例:
public class SystemTest {
public static void main(String[] args) {
try {
Properties properties = System.getProperties();//获取当前系统的所有信息
System.out.println(properties.getProperty("os.name"));//获取“os.name”(操作系统名称)的信息
} catch (Exception e) {
e.printStackTrace();
}
}
输出结果:
Windows 8.1
获取获取当前系统环境变量的方法
public static Map<String,String> getenv() //获取素有当前系统的环境变量
public static String getenv(String name) //获取指定的环境变量,若不存在该变量则返回null
例:找到并输出adb所在的目录public class AdbFounder {
public static void main(String[] args) {
//首先获取ANDROID_HOME的变量值
String androidPath = System.getenv("ANDROID_HOME");
/*若找不到ANDROID_HOME,adb也自然找不到
* adb在android sdk目录下的platform-tools文件夹里,
* sdk目录加上\platform-tools即为adb所在目录
*/
if(androidPath==null)
System.out.println("无法找到adb.exe");
else{
String adbPath=androidPath+"\\platform-tools";
System.out.println("adb.exe所在目录为:\n"+adbPath);
}
}
}
使用getenv方法,找到ANDROID_HOME的变量值,在其基础上加上/platform-tools即可
获取当前系统时间的方法
currentTimeMillis() // 获取当前系统时间与1970年1月1日0时整对比毫秒数
nanoTime() // 获取当前系统时间与1970年1月1日0时整对比纳秒数
这两个方法常用于计时
Runtime类
Runtime代表java程序的运行环境,每一个java程序运行时都会有一个对应的Runtime实例。程序不可以创建Runtime实例,但可以通过getRuntime()方法获取也当前程序运行环境相对应的Runtime实例
Runtime类有与当前内存相关的方法,请看如下程序
public class RuntimeTest {
public static void main(String[] args) {
Runtime runtime=Runtime.getRuntime();
System.out.println("处理器数量"+runtime.availableProcessors());
System.out.println("空闲内存数"+runtime.freeMemory());
System.out.println("总内存数"+runtime.totalMemory());
System.out.println("可用最大内存数"+runtime.maxMemory());
}
处理器数量4
空闲内存数63144768
总内存数64487424
可用最大内存数935854080
<
另外,也可以使用Runtime类运行某个外部的程序,使用的是exec方法
例:
>public class RuntimeTest {
public static void main(String[] args) {
Runtime runtime=Runtime.getRuntime();
try {
runtime.exec("notepad.exe");//notepad.exe是windows记事本
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
此程序运行时,会打开一个记事本