You are on page 1of 30

第十三课

Java 控制台应用程序设

本课内容

 Java 命令行参数和系统属性
 标准 I/O ,文件 I/O
 常用系统类
 Collection 接口系列
 Deprecation 类、属性和方法
命令行参数
 在启动 Java 应用程序时可以一次性地向应用
程序中传递 0~ 多个参数 ---- 命令行参数
 命令行参数使用格式:
java ClassName lisa "bily" "Mr Brown"
 命令行参数被系统以 String 数组的方式传递给
应用程序中的 main 方法,由参数 args 接收
public static void main(String[] args)
0901

命令行参数用法举例
1 public class Test13_1 {
2 public static void main(String[] args) {
3 for ( int i = 0; i < args.length; i++ ) {
4 System.out.println("args[" + i + "] = " + args[i]);
5 }
6 }
7 }

// 运行程序 Test13_1.java
java Test13_1 lisa "bily" "Mr Brown"
// 输出结果:
args[0] = lisa
args[1] = bily
args[2] = Mr Brown
系统属性 (Syst em
Propert ies)

 在 Java 中,系统属性起到替代环境变量的作用 ( 环境
变量是平台相关的 )
 可使用 System.getProperties() 方法获得一个
Properties 类的对象,其中包含了所有可用的系统属
性信息
 可使用 System.getProperty(String name) 方法获得特定
系统属性的属性值
 在命令行运行 Java 程序时可使用 -D 选项添加新的系
统属性
Properties 类

 Propert ies 类可实现属性名到属性值的映射,


属性名和属性值均为 St ring 类型 .
 Propert ies 类的 propertyNames() 方法可以
返回以 Enumeration 类型表示的所有可用系统属性
属性名 .
 Propert ies 类的 getProperty(String key) 方法获
得特定系统属性的属性值 .
 Propert ies 类的 load 和 save 方法可以实现将系
统属性信息写入文件和从文件中读取属性信息 .
0902

系统属性用法举例
import java.util.Properties;
import java.util.Enumeration;
public class Test13_2 {
public static void main(String[] args) {
Properties ps = System.getProperties();
Enumeration pn = ps.propertyNames();
while ( pn.hasMoreElements() ) {
String pName = (String) pn.nextElement();
String pValue = ps.getProperty(pName);
System.out.println(pName + "----" + pValue);
}
}
}
// java -DmyProperty=MyValue Test13_2
I/O 控制台 (Console I/O)

 System.out 提供向“标准输出”写出数据的功能
System.out 为 PrintStream 类型 .
 System.in 提供从“标准输入”读入数据的功能
System.in 为 InputStream 类型 .
 System.err 提供向“标准错误输出”写出数据的功能
System.err 为 PrintStream 类型 .
向标准输出写出数据

System.out/System.err 的 println/print 方法
 println 方法可将方法参数输出并换行
 print 方法将方法参数输出但不换行
 print 和 println 方法针对多数数据类型进行了重写
(boolean, char, int, long, float, double 以及 char[],
Object 和 String).
 print(Object) 和 println(Object) 方法中调用了参数
的 toString() 方法,再将生成的字符串输出
0903

从标准输入读取数据
import java.io.*;
public class Test13_3 {
public static void main (String args[]) {
String s;
// 创建一个 BufferedReader 对象从键盘逐行读入数据
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(isr);
try {// 每读入一行后向显示器输出
s = br.readLine();
while (!s.equals("")) {
System.out.println("Read: " + s);
s = br.readLine();
}
br.close(); // 关闭输入流
} catch (IOException e) { // 捕获可能的 IOException.
e.printStackTrace();
}
}
}
Ex1 Inptut/Output

1. 练习 P4 页 Example ,体会命令行参数的使用

2. 练习 P7 页 Example ,理解系统属性的含义和
用法;
3. 练习 P10 页 Example ,初步认识 java 语言的
输入 / 输出机制;
文件输入输出

 java.io 包中定义与数据输入、输出功能有关的类
,包括提供文件操作功能的 File 类
 创建 File 类对象
File f;
f = new File("Test.java");
f = new File("E:\\ex\\","Test.java");
 在 Java 中,将目录也当作文件处理 File 类中提供
了实现目录管理功能的方法
File path = new File("E:\\ex\\");
File f = new File(path, "Test.java");
File 类方法介绍
 关于文件 / 目录名操作  获取常规文件信息操作
String getName() long lastModified()
String getPath() long length()
String getAbsolutePath() boolean delete()
String getParent()
boolean renameTo(File newName)

 File 测试操作  目录操作


boolean exists() boolean mkdir()
boolean canWrite() String[] list()
boolean canRead()
boolean isFile()
boolean isDirectory()
boolean isAbsolute();
文件 I/O 有关类型

 文件输入
– 可使用 FileReader 类以字符为单位从文件中读入数

– 可使用 BufferedReader 类的 readLine 方法以行为单
位读入一行字符
 文件输出
– 可使用 FileWriter 类以字符为单位向文件中写出数

– 使用 PrintWriter 类的 print 和 println 方法以行为单
位写出数据
文件输入举例
import java.io.*;
public class Test13_4 {
public static void main (String[] args) {
String fname = "Test13_4.java";
File f = new File(fname);
try {
FileReader fr = new FileReader(f);
BufferedReader br = new BufferedReader(fr);
String s = br.readLine();
while ( s != null ) {
System.out.println(" 读入 : " + s);
s = br.readLine();
}
br.close();// 关闭缓冲读入流及文件读入流的连接
.
} catch (FileNotFoundException e1) {
System.err.println("File not found: " + fname);
} catch (IOException e2) {
e2.printStackTrace();
}
}
文件输出举例
import java.io.*;
public class Test13_5 {
public static void main (String[] args) {
File file = new File("tt.txt");
try {
InputStreamReader is = new InputStreamReader(System.in);
BufferedReader in=new BufferedReader(is);
PrintWriter out = new PrintWriter(new FileWriter(file));
String s = in.readLine();
while (!s.equals("")) {// 从键盘逐行读入数据输出到文件
out.println(s);
s = in.readLine();
}
in.close(); // 关闭 BufferedReader 输入流 .
out.close(); // 关闭连接文件的 PrintWriter 输出流 .
}catch (IOException e) {System.out.println(e); }
}
}
Ex2 File Input/Output

1. 分析并运行 P15 页例子,结合命令行参数的


使用,练习从已经存在的文件中读入数据并
显示的过程;
3. 分析并运行 P16 页例子,结合命令行参数的
使用,练习从标准输入中读入数据并将数据
写到文件中的过程;
Math 类

 Math 类中定义了多个 static 方法提供常用数学


运算功能
– 截断操作 (Truncation): ceil, floor, round
– 取最大、最小及绝对值 : max, min, abs
– 三角函数 : sin, cos, tan, asin, acos, atan,
toDegrees,
toRadians
– 对数运算 : log , exp
– 其它 : sqrt, pow, random
– 常量 : PI, E
String 类
 String 类对象保存不可修改的 Unicode 字符序列
 String 类的下述方法能创建并返回一个新的 String 对
象: concat, replace, substring, toLowerCase,
toUpperCase, trim,String.
 提供查找功能的有关方法 : endsWith, startsWith,
indexOf, , lastIndexOf.
 提供比较功能的方法 : equals, equalsIgnoreCase,
compareTo.
 其它方法 : charAt , length.
StringBuffer 类

 StringBuffer 类对象保存可修改的
Unicode 字符序列
 构造方法
– StringBuffer()
– StringBuffer(int capacity)
– StringBuffer(String initialString)
 实现修改操作的方法 :
– append, insert, reverse, setCharAt, setLength.
Ex3
1. 编写程序,练习 Math, String,
StringBuffer 类中有关方法的使用

可参考 jdk1.3\docs 文档
Collect ion API

 Collection API 提供“集合”的功能


 Collection API 包含下述接口
– Colection: 将一组对象以集合元素的形式组织到一
起,在其子接口中分别实现不同的组织方式
– Set: Collection 的子接口,不记录元素的保存顺序
,且不允许有重复元素
– List: Collection 的子接口,记录元素的保存顺序,
且允许有重复元素
Collection API 层次结构
<<interface>>
Collection

+add(element : Object) : boolean


+remove(element : Object) : boolean
+size() : boolean
+isEmpty() : boolean
+contains(element : Object) : boolean
+iterator() : Iterator

<<interface>> <<interface>>
Set List

HashSet ArrayList Vector


Set 接口用法举例
import java.util.*;
public class Test13_6 {
public static void main(String[] args) {
HashSet h = new HashSet();
h.add("1st");
h.add("2nd");
h.add(new Integer(3));
h.add(new Double(4.0));
h.add("2nd"); // 重复元素 , 未被加入
h.add(new Integer(3)); // 重复元素 , 未被加入
m1(h);
}
public static void m1(Set s){
System.out.println(s);
}
}
// 本应用程序输出结果如下 :[1st, 3, 2nd, 4.0]
List 接口用法举例
import java.util.*;
public class Test13_7{
public static void main(String[] args) {
ArrayList h = new ArrayList();
h.add("1st");
h.add("2nd");
h.add(new Integer(3));
h.add(new Double(4.0));
h.add("2nd"); // 重复元素 , 加入
h.add(new Integer(3)); // 重复元素 , 加入
m1(h);
}
public static void m1(List s){
System.out.println(s);
}
}
// 本应用程序输出结果如下 :[1st, 2nd, 3, 4.0, 2nd, 3]
Deprecat ion

 Deprecat ion 关键字可用于标记类、属性和方法


,表明这些类,属性或方法已过时、不再提倡使
用.
 Deprecat ion 成分均存在相应的替代类、属性或
方法,这些替代者可能采用了更标准化的命名惯
例、或功能更适用 .
 在移植 Java 代码时,可使用 – deprecat ion 选
项获得有关的详细信息 .
javac -deprecation MyFile.java
Deprecat ion 举例 (1)
public class HelloWorld{
public static void main(String args[]){
String f;
f = System.getenv("java.class.path");
System.out.println(f);
}
}

编译 : javac HelloWorld.java 输出结果 :


HelloWorld.java uses or overrides a deprecated API. Recompile with
"-deprecation" for details.
1 warning
Process completed.
Deprecat ion 举例 (2)
public class HelloWorld{
public static void main(String args[]){
String f;
f = System.getenv("java.class.path");
System.out.println(f);
}
}

再次编译 : javac –deprecation HelloWorld.java 输出结果 :


HelloWorld.java:4: Note: The method java.lang.String getenv(java.lang.String)
in class java.lang.System has been deprecated.
f = System.getenv("java.class.path");
^
HelloWorld.java uses or overrides a deprecated API. Please consult the
documentation for a better alternative.
1 warning
Process completed.
Deprecat ion 举例 (3)

public class HelloWorld{


public static void main(String args[]){
String f;
f = System.getProperty("java.class.path");
System.out.println(f);
}
}

修改后编译通过
运行输出结果 :
D:\lgz\ex;C:\jdk1.3\jre\lib\rt.jar;C:\jdk1.3\jre\lib\i18n.jar;C:\jdk1.3\lib\dt.jar;
C:\jdk1.3\lib\tools.jar
Ex4
1. 运行 P23,24 页的例子,体会 Set 与
List 接口的区别;
2. 理解 P26,28 页程序,查看
jdk1.3\docs 文档理清各种数据类型
的性能及用法;体
会“ Deprecat ion” 方法及其处理
方式。 ( 选做 )

You might also like