The Java™ Tutorials——(3)Essential Classes——The Platform Environment

平台环境(The Platform Environment)

​ Java应用运行在平台环境中,平台环境包括底层的操作系统,Java虚拟机(JVM),类库,还有程序启动时各种配置数据。本章会讲解的API,应用程序会使用它们来检查,配置它的平台环境。

​ 主要包括三个部分:

  • 配置工具集。应用程序部署时用来访问配置数据的API,帮助应用访问其启动上下文。
  • 系统工具集。SystemRuntime类定义的混杂API。
  • PATHCLASSPATH。配置JDK开发工具和应用的环境变量。

1. 配置工具集

1.1 Properties

Propertieskey/value键值对的配置数据。key和value都是String值,

package java.util;
public class Properties extends Hashtable<Object,Object> {
   
}

​ 为了管理properties,我们需要创建 java.util.Properties 实例,此类提供了下列方法

  • 从流中导入key/value键值对形成Properties 对象
  • 根据key取出value
  • 列出key及其value
  • 枚举key
  • 保存Properties 为流

properties继承的HashTable的方法支持如下行为:

  • 测试特定的key或者value,看其是否在Properties 对象中

  • 获得key/value对的数量

  • 移除特定的key/value

  • 添加key/value对到Properties 对象中

  • 枚举key或者value

  • 通过key取出value

  • 查看是否Properties 对象为空

System 类维护着一个Properties 对象,它定义了当前工作环境的配置项。这个后面的系统属性(System Properties)小结会讲。

​ 下面我们来看看应用程序生命周期中的Properties 对象。

																/*

			Loads default properties from 
			 well-known default location.      ↘
					                             ↘
					  ↓                           ↓
					                              ↓
			Loads values from last invocation     ↓
			 from well-known location.			  ↘→ Starting
			 		                              ↗→ Up
			 		  ↓                           ↑
			 		  							  ↑
			Initializes itself based on default  ↗
			 and remembered properties.        ↗
			 		
			 		  ...
			 		
			Set or modifies various properties ↘ → Runing
			 based on user interaction.        ↗ →
			 		
			 		  ... 
			 		  
			Saves values to well-known lovaltion↘ → Exiting
			 for next time.					    ↗ →


																*/

​ 下面的代码演示了:导入默认properties,导入remembered properties。

. . .
// create and load default properties
Properties defaultProps = new Properties();
FileInputStream in = new FileInputStream("defaultProperties");
defaultProps.load(in);
in.close();

// create application properties with default
Properties applicationProps = new Properties(defaultProps);

// now load properties 
// from last invocation
in = new FileInputStream("appProperties");
applicationProps.load(in);
in.close();
. . .

​ 下面的代码演示如何保存properties

FileOutputStream out = new FileOutputStream("appProperties");
applicationProps.store(out, "---No Comment---");
out.close();

​ 一旦应用装配好Properties 对象,应用就能查询对象的各种各样的信息。

contains(Object value) and containsKey(Object key)
getProperty(String key) and getProperty(String key, String default)
list(PrintStream s) and list(PrintWriter w)
elements(), keys(), and propertyNames()
stringPropertyNames()
size()

​ 设置properties。

setProperty(String key, String value)
remove(Object key)

1.2 命令行参数

​ 简单使用:

public class Echo {
    public static void main (String[] args) {
        for (String s: args) {
            System.out.println(s);
        }
    }
}

/* java Echo Drink Hot Java
Drink
Hot
Java
*/

​ 支持数字的参数:

int firstArg;
if (args.length > 0) {
    try {
        firstArg = Integer.parseInt(args[0]);
    } catch (NumberFormatException e) {
        System.err.println("Argument" + args[0] + " must be an integer.");
        System.exit(1);
    }
}

​ 所有的Number 类— Integer, Float, Double类都有parseXXX方法。

1.3 环境变量

Java平台使用System.getenv方法来获取环境变量,获取到的Map实例是只读的。

// java.lang.System
public static Map<String,String> getenv()
    
public static String getenv(String name)// 通过key来查找
public class EnvMap {
    public static void main (String[] args) {
        Map<String, String> env = System.getenv();
        for (String envName : env.keySet()) {
            System.out.format("%s=%s%n",
                              envName,
                              env.get(envName));
        }
    }
}
public class Env {
    public static void main (String[] args) {
        for (String env: args) {
            String value = System.getenv(env);
            if (value != null) {
                System.out.format("%s=%s%n",
                                  env, value);
            } else {
                System.out.format("%s is"
                    + " not assigned.%n", env);
            }
        }
    }
}
/*java env.Env classpath
classpath=.;C:\Program Files\Java\jdk1.8.0_191\lib;C:\Program Files\Java\jdk1.8.0_191\lib\tools.jar

java env.Env java_home
java_home=C:\Program Files\Java\jdk1.8.0_191
*/

​ 当Java应用使用 ProcessBuilder对象创建新进程时,默认传入新进程的环境变量集合与JVM的环境变量集合一样的。如果想自定义,可以通过使用ProcessBuilder.environment方法来改变环境变量集合。

2. 系统工具集(System Utilities)

System类实现了许多系统工具,其中有基本的命令行I/O操作,可查看本文章同系列文章的I/O章节部分。

2.1 系统属性

System类维护了一个Properties 对象,它描述了当前工作环境的配置项。System properties包括的信息有:当前用户,当前Java运行时版本,分割路径名的分隔符

​ 下面列出了一些最重要的系统属性信息:

KeyMeaning
"file.separator"Character that separates components of a file path. This is “/” on UNIX and “\” on Windows.
"java.class.path"Path used to find directories and JAR archives containing class files. Elements of the class path are separated by a platform-specific character specified in the path.separator property.
"java.home"Installation directory for Java Runtime Environment (JRE)
"java.vendor"JRE vendor name
"java.vendor.url"JRE vendor URL
"java.version"JRE version number
"line.separator"Sequence used by operating system to separate lines in text files
"os.arch"Operating system architecture
"os.name"Operating system name
"os.version"Operating system version
"path.separator"Path separator character used in java.class.path
"user.dir"User working directory
"user.home"User home directory
"user.name"User account name

2.2.1 读系统属性

System 类的两个方法:getProperty and getProperties.

// java.lang.System
static String	getProperty(String key)

static String	getProperty(String key, String def)// 如果key对应值不存在则返回默认值def
    
public static Properties getProperties() // 获取一个key/values键值对对象。

​ 举个例子:

System.getProperty("path.separator");
2.2.2 写系统属性

​ 修改已存在的系统属性,可使用System.setProperties

警告!!,修改系统属性有潜在风险,应该慎重考虑。

public synchronized Object setProperty(String key, String value) {
    return put(key, value);
}

​ 下面是一个例子:

/* 其中myProperties.txt的内容为:
subliminal.message=Buy StayPuft Marshmallows!
*/

public static void main(String[] args)
        throws Exception {

    // set up new properties object
    // from file "myProperties.txt"
    FileInputStream propFile =
        new FileInputStream( "myProperties.txt");
    Properties p =
        new Properties(System.getProperties());
    p.load(propFile);

    // set the system properties
    System.setProperties(p);
    // display new properties
    System.getProperties().list(System.out);
}

2.2 The Security Manager

The Security Manager

2.3 System其它方法

2.3.1 arrayCopy

这个我们在语言基础章节的数组讲过,这里不重复

2.3.2 currentTimeMillisnanoTime

​ 这两个方法对于测量程序执行的事件间隔有好处。

​ 测量毫秒级别的事件间隔,我们可以调用两此currentTimeMillis 方法,相减即可。

​ 测量那秒级别的时间间隔,我们则可以使用nanoTime 方法。

​ 注意,这两个方法的精确性得看操作系统提供的时间服务;不要精确的认为这两个方法能最接近地表示毫秒,纳秒。这两个方法不应该用来表示当前的时间。更加高级的用法,我们可以参考java.util.Calendar.getInstance

2.3.3 exit

方法会导致JVM关闭,传入的一个整型参数表示退出状态,我们默认0表示正常退出。

3. PATH 与CLASSPATH

3.1 Windows下PATH

PATH 环境变量是为了方便运行,我们不必在找到java根目录/bin,然后执行,而可以直接在系统任意目录下执行。

%JAVA_HOME%\bin;%SystemRoot%\system32;%SystemRoot%;%SystemRoot%\System32\Wbem

// JAVA_HOME环境变量已经设置过了,我们通过 %JAVA_HOME% 引用

​ 代码示例:

..> echo %SystemRoot%
C:\Windows
3.2 Solaris/Linux下Path
// 使用完整路径运行
% /usr/local/jdk1.8.0/bin/javac MyClass.java


// 1. C shell (csh)下,编辑startup文件(~/.cshrc)
set path=(/usr/local/jdk1.7.0/bin $path)
    
// 2. bash下,编辑startup文件(~/.bashrc)
PATH=/usr/local/jdk1.7.0/bin:$PATH
export PATH

// 3. ksh下,startup文件被命名为ENV,
PATH=/usr/local/jdk1.7.0/bin:$PATH
export PATH

// 4. sh下,编辑profile文件(~/.profile)
PATH=/usr/local/jdk1.7.0/bin:$PATH
export PATH


// 导入startup文件,并验证path被设置了

// 1. C shell (csh)下
% source ~/.cshrc
% java -version

// 2. ksh, bash, or sh下
% . /.profile
% java -version
3.3 CLASSPATH

CLASSPATH 用来告诉应用程序,哪里包含JDK tools,去哪里搜索用户类。

​ 手动指定classpath建议使用-cp命令可选项。这个命令选项只对当前运行的程序有影响。

​ 默认CLASSPATH“.”,意味着只有当前目录被搜索,CLASSPATH 或者-cp命令能够重写此值。

// 检查 CLASSPATH 是否设置

// 1. Win下
..> echo %CLASSPATH%
    
// 2. Solaris 或 Linux下
% echo $CLASSPATH

更多CLASSPATH内容,点击参考文章。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值