分享

JDK 6 探秘之三:Java.lang包的新特性

 goldbomb 2006-12-17

Java平台中的基础包有java.lang和java.util, 这两个包是非常重要的,这两个包在JDK 6中有给我们带来了什么新东西了呢? 下面就先来看看java.lang包吧:

6.0 的java.lang包只是比5.0中多两个类. 但是不要以为只多了2个类就没有什么新东西了吧. 其实从数量上是不可以看出本质了, 有很多5.0以前的类都增加了新的方法. 我们主要来看看6.0中我们常用的特性.

在6.0 的System类中添加了一个console()方法. 用来与控制台输入(出)交互. 另外通过Console的printf()函数还可以避免非通用ASCII字符(主要是非英文字符)输出的问题. 下面来看个示例:

public class Output {
  public static void main(String args[]) {
    String string = "Español";
    System.out.println(string);
    System.console().printf("%s%n", string);
  }
}

上面的字符中含有一个 ñ 字符, 非ASCII字符, 输出结果为:

> java Output
Espa±ol
Español

可以看到使用  System.out.println 输出时, 非ASCII字符, 给截断了. 而console可以正确的输出.

上面只是Console http://java./javase/6/docs/api/java/io/Console.html 类的一个应用, 该类还有其他几个有用的函数, 如 从控制台读取字符或者密码字段. 下面来看个例子,注意 读取字符和密码的不同:

import java.io.Console;

public class Input {
  public static void main(String args[]) {
    Console console = System.console();
    console.printf("Enter name: ");
    String name = console.readLine();
    char password[] = console.readPassword("Enter password: ");
    console.printf("Name:%s:\tPassword:%s:%n",name, new String(password));
  }
}

运行结果:

G:\JDK6>java Input
Enter name: icess
Enter password:
Name:icess:     Password:icess:

在输入秘密的时候, 和linux登陆时候输入密码一样,没有回显.

另外Lang包中的String类添加了一个新分方法,isEmpty(), 该方法应该是从Apache 的common 组件中引入的. 下面看个例子:

public class EmptyString {
  public static void main(String args[]) {
    String one = null;
    String two = "";
    String three = "non empty";
    try {
      System.out.println("Is null empty? : " + one.isEmpty());
    catch (NullPointerException e) {
      System.out.println("null is null, not empty");
    }
    System.out.println("Is empty string empty? : " + two.isEmpty());
    System.out.println("Is non empty string empty? : " + three.isEmpty());
  }
}

 

输出结果:

G:\JDK6>java EmptyString
null is null, not empty
Is empty string empty? : true
Is non empty string empty? : false

上面是lang包中在6.0版本引入的主要新功能,下次来看看util包中有什么变化.

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多