第 5章 Java资源及其利用
第 5章 Java资源及其利用
?Java的标准库结构
? 语言包
?输入与输出包
?其他常用资源简介
Java的标准库结构
Java有一个功能强大的资源库,通过类和类
的继承机制将资源库中的资源组织起来。
Java资源库中类的继承层次和包的组织呈树
型结构,它将功能相关的类组织成包,使程
序员可以很方便地使用资源库。
常用的包
?java.lang包:主要含有与语言相关的类
?java.io包:主要含有与输入输出相关的类
java.util包:包括许多具有特定功能的类,有
Arrays,Date,Calendar和 Stack等
?java.swing包:提供了创建图形用户界面元素
的类
?java.net包:含有与网络操作相关的类
?java.applet包:含有控制 Hotjava 浏览器的类
Java资源的层次结构
语言包
?基本对象类
?系统类
?包装类
?字符串类和缓冲串类
?数学类
?异常处理
基本对象类
?Object类是所有 Java类的祖先,它处于 Java
开发环境的类层次树的根部,所有其他类都
是由 Object类直接或间接派生出来的。如果
一个类在定义的时候没有包含 extends关键字,
编译器会将其建为 Object类的直接子类。
Object类的常用方法
方法 说明
protected Object clone( ) 生成并返回当前对象的一个拷贝。
public boolean equals (Object
obj) 比较两个对象是否相同,结果为一布尔值。
public final Class getClass( ) 返回一个对象在运行时所对应的类的表示,从 而可以得到相关的类的信息。
protected void finalize( )
throws Throwable 定义回收当前对象时所需完成的清理工作。
public String toString( ) 返回描述当前对象的字符串信息。
Object类的方法的个例
class ObjectExam{
public static void main(String[ ] args){
Integer a = new Integer(1);
Integer b = new Integer(1);
Rectangle c = new Rectangle(20,5);
System.out.println(a.equals(b));
System.out.println("The Object's class is:" + a.getClass());
System.out.println(c.toString());
/*toString()方法返回的是该对象所对应的类名、一个 @符号和
一个该对象的 hash码的无符号十六进制描述。用户通过重载
toString()方法可以适当地显示对象的信息以进行调试。 */
}
}
系统类
?System类( System Class)是一个功能强大、
极其有用的特殊的类,它提供了标准输入、
标准输出和标准错误输出;对系统信息的存
取;快速拷贝数组元素等等机制
?System类由 public final 修饰,该类不能被实
例化(即不能创建 System类的对象)或派生
子类。 System类中包含了许多有用的类变量
和类方法(由 static修饰)
System类的变量及其说明
类变量 说明
public static final PrintStream err 标准错误输出流。
public static final InputStream in 标准输入流。
public static final PrintStream out 标准输出流。
System类常用的方法及其说明
方法 说明
public static void arraycopy(Object src,int
src_position,Object dst,int dst_position,int length)
拷贝一个数组到另一个数组, 它从源数组的
指定位置开始, 拷贝到目标数组的指定
位置 。
public static long currentTimeMillis()
返回从时间 1970年 1月 1日 00:00:00时起到当
前所历经的毫秒数 ( 通常用来比较两事
件发生的前后时间差 ) 。
public static void exit(int status) 退出 Java当前运行的虚拟机 。
public static void gc() 运行垃圾回收器 。
public static String getProperty(String key) 获取由给定的 key确定的系统属性值 。
public static void setErr (PrintStream err) 重定向标准错误输出设备 。
public static void setIn (InputStream in) 重定向标准输入设备 。
public static void setOut (PrintStream out) 重定向标准输出设备 。
public static String setProperty(String key,
String value)
设置由 key指定的系统属性为指定的 value的
值 。
System类的常用属性列表
系统属性名称( key的取值) 含义
"file.separator" 文件分隔符
"java.class.path" Java类路径
"java.class.version" Java类的版本编号
"java.home" Java的安装目录
"java.version" Java的版本编号
"os.arch" 操作系统的体系结构
"os.name" 操作系统名
"os.version" 操作系统版本
"line.separator" 行分隔符
"path.separator" 路径分隔符
"user.dir" 用户当前目录
"user.home" 用户主目录
"user.name" 用户名
System类的例子
public class SystemDemo{
public static void main(String args[ ]) throws Exception{
char c;
System.out.println("请输入一个字符,");
c = (char)System.in.read();
System.out.println("你输入了," + c);
System.out.println("System.currentTimeMillis()=" + System.currentTimeMillis());
System.out.println("java.version=" + System.getProperty("java.version"));
System.out.println("java.home=" + System.getProperty("java.home"));
System.out.println("java.vm.name=" + System.getProperty("java.vm.name"));
System.out.println("java.class.path=" + System.getProperty("java.class.path"));
System.out.println("user.home=" + System.getProperty("user.home"));
System.out.println("user.dir=" + System.getProperty("user.dir"));
System.out.println("user.name=" + System.getProperty("user.name"));
System.out.println("os.name=" + System.getProperty("os.name"));
System.out.println("os.arch=" + System.getProperty("os.arch"));
System.out.println("os.version=" + System.getProperty("os.version"));
System.out.println("file.separator=" + System.getProperty("file.separator"));
System.out.println("path.separator=" + System.getProperty("path.separator"));
}
}
包装类
?为确保 Java语言的纯面向对象特性,
java.lang包为基本数据类型提供了一些对象
封装。在 Java中,数据类型包装类( type
wrapper class)用于封装基本数据类型的有
关信息和操作
?数据类型包装类是由多个类组成的一个集合,
每种基本数据类型均存在相应的对象封装类
包装类及其对应的基本数据类型
基本数据类型 数据类型包装类
byte Byte
short Short
int Integer
long Long
float Float
double Double
char Character
boolean Boolean
包装类的一些共同的方法
方法 说明
public String
toString()
返回数据类型包装类中所保存数据的
字符串表示形式 。
public type
typeValue()
返回数据类型包装类的相关基本类型
值 。
public boolean
equals(Objec
t obj)
由于数据类型包装类不能直接用等号
来进行比较, 因此需要用到这个方
法 。
数据类型包装类的例
public class Exam {
public static void main(String args[ ]) { //构造方法
Integer a = new Integer(1);
Boolean b = new Boolean(true);
Float f = new Float(-2.4);
Double d = new Double(1.4);
Character ch = new Character('A');
Character ch2 = new Character('A'); //方法
int i = a.intValue( );
char c = ch.charValue( );
System.out.println(i);
System.out.println(b.booleanValue( ));
System.out.println(f.floatValue( ));
System.out.println(d.doubleValue( ));
System.out.println(c);
System.out.println(ch.equals(ch2));
System.out.println(d.toString( ));
}
}
Character类
?Character类的继承树是,
java.lang.Object
|
+---java.lang.Character
?它的构造方法很简单,
public Character(char value)
Character类的一些常用方法及其说明
方法 说明
public static boolean isLowerCase(char ch) 如果 ch是小写, 则返回 true,否则返回 false。
public static boolean isUpperCase(char ch) 如果 ch是大写, 则返回 true,否则返回 false。
public static boolean isDigit(char ch) 如果 ch是数字, 则返回 true,否则返回 false。
public static boolean isLetter(char ch) 如果 ch是字母, 则返回 true,否则返回 false。
public static char toLowerCase(char ch) 返回给定字母 ch对应的小写形式 。
public static char toUpperCase(char ch) 返回给定字母 ch对应的大写形式 。
public static int digit(char ch,int radix) 根据 radix指明的基数, 返回 ch所对应的数值 。
Character类的应用示例
public class CharacterExam{
public static void main(String args[ ]) { //构造方法
Character ch = new Character('s');
char c = ch.charValue(); //方法
if (Character.isUpperCase(c))
System.out.println("The character " + c + " is upper case.");
else
System.out.println("The character " + c + " is lower case.");
boolean b = Character.isDigit(c);
int x = Character.digit('c',16); //十六进制中,c代表 12。
System.out.println("b=" + b);
System.out.println("x=" + x);
}
}
Integer类
? Integer类的继承树是,
java.lang.Object
|
+--java.lang.Number
|
+--java.lang.Integer
? Integer类有两种构造方法,
⑴ public Integer(int value)
⑵ public Integer(String s) throws
NumberFormatException
Integer类的常用类变量及其说明
类变量 说明
public static final int MAX_VALUE 规定了 int类型的最大值 。
public static final int MIN_VALUE 规定了 int类型的最小值 。
Integer类的常用方法及其说明
方法 说明
public static int parseInt(String s)
throws NumberFormatException
将字符串 s转换为带符号十进制整数, 结果
为 int量 。
public static Integer valueOf(String s)
throws NumberFormatException
将字符串 s转换为一个 Integer对象, 该对象
对应的 int数值与字符串表示的数值一致 。
Integer类的应用示例
public class IntegerExam{
public static void main(String args[ ]) { //构造方法
Integer a = new Integer(1);
Integer a2 = new Integer(“1”); //方法
int i = a.intValue( );
int i2 = Integer.valueOf("111").intValue( );
int i3 = Integer.parseInt("888");
System.out.println(i);
System.out.println(i2);
System.out.println(i3);
System.out.println(a.equals(a2));
byte largestByte = Byte.MAX_VALUE;
short largestShort = Short.MAX_VALUE;
int largestInteger = Integer.MAX_VALUE;
int smallestInteger = Integer.MIN_VALUE;
long largestLong = Long.MAX_VALUE;
float largestFloat = Float.MAX_VALUE;
double largestDouble = Double.MAX_VALUE;
System.out.println("The largest byte value is " + largestByte);
System.out.println("The largest short value is " + largestShort);
System.out.println("The largest integer value is " + largestInteger);
System.out.println("The smallest integer value is " + smallestInteger);
System.out.println("The largest long value is " + largestLong);
System.out.println("The largest float value is " + largestFloat);
System.out.println("The largest double value is " + largestDouble);
}
}
字符串与各种数据类型之间的转化
public class TransformExam{
public static void main(String args[ ]) { //字符串与整型之间的转化
Integer a = new Integer(1);
String s = a.toString();
System.out.println("s=" + s);
int i = Integer.parseInt("888");
int i2 = Integer.valueOf("666").intValue();
System.out.println("i=" + i);
System.out.println("i2=" + i2); //字符串与浮点数之间的转化
Double x = new Double(1.7);
String s2 = x.toString( );
System.out.println("s2=" + s2);
double d = Double.valueOf("12.3").doubleValue( );
float f = Float,valueOf("-.3"),floatValue( );
System.out.println("d=" + d);
System.out.println("f=" + f);
}
}
字符串类和缓冲串类
?java.lang包中专门提供了两个类
String
StringBuffer
来处理字符串,前者用来处理创建之后不会
再做修改和变动的字符串,后者则用来处理
创建之后允许再做修改和变动的字符串。这
两个类共同的特点是都不能再派生子类
String类
?String类描述了字符串,所有 Java程序中的字
符串字面量,是作为该类的实例来实现的
?String类的继承树是,
java.lang.Object
|
+--java.lang.String
String类提供的构造方法
?public String ();
?public String (char chars[ ]);
?public String (char chars[ ],int startIndex,int
numChars);
?public String(String value)
?public String(StringBuffer buffer)
String类的常用方法及其说明
方法 说明
public int length( ) 返回当前字符串的长度 。
public String toLowerCase ( ) 将当前字符串中的所有大写字母转换为小写 。
public String toUpperCase ( ) 将当前字符串中的所有小写字母转换为大写 。
public String trim( ) 去掉当前字符串中的前导空格和末尾的空格 。
public String substring (int
beginIndex)
返回当前字符串中从 beginIndex位置开始到末尾的子串 。
public String substring (int
beginIndex,int endIndex)
返回当前字符串的子串, 该子串由 beginIndex( 包含在内 ) 和
endIndex( 不包含在内 ) 之间的字符组成 。
public String replace(char
oldChar,char newChar)
将当前字符串中的所有出现的 oldChar用 newChar替换, 生成
一个新字符串 。
public char charAt(int index) 返回指定索引位置上的字符 。 索引范围在 0与 length()-1之间 。
public void getChars (int
srcBegin,int srcEnd,char dst[ ],int
dstBegin)
将当前字符串的部分字符拷贝到目标字符数组 dst中 。 部分字
符是指此字符串中从 srcBegin( 包含在内 ) 到 srcEnd( 不包含
在内 ) 之间的字符 。 拷贝到目标字符数组中的字符从 dstBegin
位置开始存放 。
public boolean equals (Object
anObject)
将当前字符串与指定对象比较, 如果两者具有相同的长度和
字符, 则返回 true,否则返回 false
public boolean equalsIgnoreCase
(String anotherString)
将当前字符串与指定对象比较, 忽略大小写的区别 。 如果两
者相等, 则返回 true,否则返回 false。
public int compareTo (String
anotherString)
将当前字符串与 anotherString进行比较, 返回一个大于, 等
于或小于 0的整数 。 此整数值决定于此字符串是大于, 等
于还是小于 anotherString字符串 。
public char[ ] toCharArray( ) 将当前字符串转换成一个字符数组 。
public byte[ ] getBytes( ) 将当前字符串转换成一个字节数组 。
public boolean startsWith (String
prefix) 判断当前字符串是否由指定的前缀 prefix开始 。
public boolean endsWith (String
suffix) 判断当前字符串是否以指定的后缀 suffix结束 。
public int indexOf(int ch) 返回当前字符串中第一次出现指定字符 ch的位置, 如果未找到则返回 -1。
public int lastIndexOf(int ch) 返回当前字符串中最后一次出现指定字符 ch的位置, 如果未找到则返回 -1。
String类的常用方法示例
public class StringDemo{
public static void main(String args[ ]){ //常用方法
String s = " Hello "; //Hello前后各有 2个空格
System.out.println("s.length()=" + s.length( ));
System.out.println("s.toLowerCase()=" + s.toLowerCase( ));
System.out.println("s.toUpperCase()=" + s.toUpperCase( ));
System.out.println("s.trim()=" + s.trim( ));
System.out.println("s.substring(5)=" + s.substring(5));
System.out.println("s.substring(3,5)=" + s.substring(3,5));
String news = s.replace('l','t'); //将 s中所有的 'l'替换为 't'以生成新串
System.out.println("replace all 'l' with 't',"+news);
String cde = "cde";
System.out.println("abc" + cde);
/*提取字符,提取一个字符,可以使用 charAt方法 ;
如需提取多个字符,可以使用 getChars方法 */
System.out.println("提取字符的结果,");
char c = s.charAt(3);
System.out.println(c);
char buf[ ] = new char[4];
s.getChars(1,5,buf,0);
System.out.println(buf); //字符串比较
System.out.println("字符串比较的结果,");
String s1="Hello";
String s2="Hello";
String s3="HELLO";
System.out.println(s1+" equals "+s2+" -> "+s1.equals(s2));
System.out.println(s1+" equals "+s3+" -> "+s1.equals(s3));
System.out.println(s1+" equalsIgnoreCase "+s3+" -> "
+s1.equalsIgnoreCase(s3));
System.out.println(s1+" compareTo "+s2+" -> "+s1.compareTo(s2));
String s4="LemonTree";
System.out.println(s4.startsWith("Lemon"));
System.out.println(s4.endsWith("Tree"));
System.out.println(s4.endsWith("tree")); //字符串检索
System.out.println("字符串检索的结果,");
System.out.println("字符 e第一次出现的位置为,"+s4.indexOf('e'));
System.out.println("字符 e最后一次出现的位置为,"+s4.lastIndexOf('e'));
}
}
StringBuffer类
? StringBuffer类用于处理可变的字符串,
StringBuffer对象的内容是可以扩充和修改的。当生
成一个 StringBuffer对象后,也可以通过调用
toString()方法将其转换为 String对象。
? StringBuffer类的继承树是,
java.lang.Object
|
+--java.lang.StringBuffer
StringBuffer类提供了三个构造方法
?public StringBuffer()
?public StringBuffer(int length)
?public StringBuffer (String str)
StringBuffer类的常用方法及其说明
方法 说明
public StringBuffer append(type
typeObjectName)
将指定的参数对象转化成 String,然后追加到当前
StringBuffer对象的末尾 。
public StringBuffer insert(int offset,type
typeObjectName)
用来在当前 StringBuffer对象的指定位置插入由参数
对象转化而得的 String内容 。
Public StringBuffer delete (int start,int end) 删除当前 StringBuffer对象的子串, 该子串中字符的位置由 start开始, 到 end – 1结束 。
public StringBuffer replace (int start,int end,
String str)
将由 start开始, 到 end – 1结束的位置处的字符序列用
str来替代 。
public StringBuffer reverse( ) 倒置当前 StringBuffer对象中的字符序列 。
public void setCharAt(int index,
char ch) 用指定字符 ch替换由 index指定的位置处的字符 。
public String toString( ) 将一个可变字符串转化为一个不变字符串 。
public int length( ) 返回当前 StringBuffer对象的长度 ( 字符数目 ) 。
public int capacity( ) 返回当前 StringBuffer对象的整个容量 。
StringBuffer类的常用方法示例
class StringBufferDemo{
public static void main(String args[ ]){ //构造方法
StringBuffer s0 = new StringBuffer( );
StringBuffer s1 = new StringBuffer(512);
StringBuffer s2 = new StringBuffer("Hello!"); //测试长度和容量
System.out.println("s0.length()=" + s0.length( ));
System.out.println("s0.capacity()=" + s0.capacity( ));
System.out.println("s1.length()=" + s1.length( ));
System.out.println("s1.capacity()=" + s1.capacity( ));
System.out.println("s2.length()=" + s2.length( ));
System.out.println("s2.capacity()=" + s2.capacity( )); //替换、删除和倒置
StringBuffer s = new StringBuffer("LenonTree");
s.setCharAt(2,'m');
System.out.println("s=" + s);
System.out.println(s.replace(0,5,"Apple"));
System.out.println(s.delete(0,5));
System.out.println("s.reverse()=" + s.reverse( ));
//追加和插入各种类型的数据
StringBuffer st = new StringBuffer("eacher!");
boolean b = true;
char c = 'T';
double d = 3.14159;
char e = ',';
char f[ ] = {'W','e','l','c','o','m','e','!'};
char g = '!';
System.out.println("insert a char:" + st.insert(0,c));
st.insert(0,e);
System.out.println("insert a double:" + st.insert(0,d));
st.insert(0,g);
System.out.println("insert a Array:" + st.insert(0,f));
System.out.println("append a char:" + st.append(c));
System.out.println("append a array:" + st.append(d));
System.out.println("append a boolean:" + st.append(b));
}
}
数学类
? java.lang.Math类是标准的数学类,提供了两个数学
常量和若干实现基本的数学操作的方法。与 System
类相似,java.lang.Math类也不能被子类化或实例化,
它的所有方法和变量也都是静态的。
? Math类的继承树是,
java.lang.Object
|
+--java.lang.Math
Math类的类变量及其说明
类变量 说明
public static final double E 最接近自然对数的底 ( e) 的 double值 。
public static final double PI 最接近圆周率 ( ?) 的 double值 。
Math类的常用方法及其说明
方法 说明
public static double sin(double a) 返回角度 a( 以弧度为单位 ) 的 sin值 。
public static double cos(double a) 返回角度 a( 以弧度为单位 ) 的 cos值 。
public static double tan(double a) 返回角度 a( 以弧度为单位 ) 的 tan值 。
public static double asin(double r) 返回 sin值为 r的角度值 。
public static double acos(double r) 返回 cos值为 r的角度值 。
public static double atan(double r) 返回 tan值为 r的角度值 。
public static double pow(double a,
double b)
返回 a的 b次方, 结果为 double型 。
public static double sqrt(double a) 返回 a的平方根, 结果为 double型 。
public static double exp(double a) 返回 ea。
public static double log(double a) 返回 a的自然对数, 即 ln a。
public static double ceil(double a) 返回不小于 ( 即大于或等于 ) 参数 a的最小整数, 结果为
double型 。
public static double floor(double a) 返回不大于 ( 即小于或等于 ) 参数 a的最大整数, 结果为
double型 。
public static double rint(double a) 返回最接近参数 a的整数, 结果为 double型 。
public static long round(double a) 返回最接近参数 a的 long值 。
public static int round(float a) 返回最接近参数 a的 int值 。
public static double random() 返回一个大于等于 0.0且小于 1.0的随机数 。
public static type abs(type a) 返回 a的绝对值 。 type可以为 int,long,float和 double型 。
结果类型与参数的相同 。
public static type max( type a,type b) 返回 a和 b的最大值 。 type可以为 int,long,float和 double
型 。 结果类型与参数的相同 。
public static type min(type a,type b) 返回 a和 b的最小值 。 type可以为 int,long,float和 double
型 。 结果类型与参数的相同 。
Math类的常用方法示例
class MathDemo{
public static void main(String args[ ]){ //常量
System.out.println("Math.E=" + Math.E);
System.out.println("Math.PI=" + Math.PI); //三角函数和反三角函

System.out.println("sin(pi/2)=" + Math.sin(Math.PI/2));
System.out.println("asin(1)=" + Math.asin(1)); //舍入
System.out.println("ceil(E)=" + Math.ceil(Math.E));
System.out.println("floor(E)=" + Math.floor(Math.E));
System.out.println("rint(PI)=" + Math.rint(Math.PI));
System.out.println("round(PI)=" + Math.round(Math.PI)); //求出 1~10之间的一个随机数
int i = (int)(Math.random( ) * 10) + 1;
System.out.println("i=" + i); //其他常用方法
System.out.println("exp(1)=" + Math.exp(1));
System.out.println("lnE=" + Math.log(Math.E));
System.out.println("sqrt(" + 25 + ")=" + Math.sqrt(25));
System.out.println("power(" + 2 + "," + 8 + ")=" + Math.pow(2,8));
System.out.println("abs(-8.2)=" + Math.abs(-8.2));
System.out.println("max(" + 2 + "," + 8 + ")=" + Math.max(2,8));
System.out.println("min(" + 2 + "," + 8 + ")=" + Math.min(2,8));
}
}
异常处理
?,异常”(又叫“例外”)指的是程序运行时出现的非正常
情况。用任何一种计算机语言设计的程序在运行时都可能出
现各种错误。常见的错误有:除数为 0、文件不能打开、数
组下标越界、内存不够等。有些错误是可以预料的、有些错
误则是不可预料的。
? 对于上述运行中的错误,计算机系统中通常采取两种处理办
法,
⑴由计算机系统本身直接检测,遇错则终止程序的运行。
⑵由程序员在程序设计过程中检测、显示提示信息并处理。
Java中异常层次结构
类 Throwable有两个直接子类
?Error类及其子类描述的是 java将字节码装入
内存的过程中和对字节码进行检查的过程中
遇到的问题,java的内部错误、资源耗尽的
情况
?Exception类对象是由 Java程序处理或抛出的
对象。它有各种不同的子类分别对应于不同
类型的异常。其子类可分成两部分:运行时
异常类和其余的异常类(一般叫非运行时异
常或检查型异常)
常见的运行时异常
?java.lang.ArithmeticException
?java.lang.ArrayIndexOutOfBoundsException
?java.lang.StringIndexOutOfBoundsException
?java.lang.ClassCastException
?java.lang.NegativeArraySizeException
检查型异常
?Exception的子类中除了运行时异常以外的部
分称为 检查型异常 。若在程序中使用的方法
会抛出检查型异常,则 Java编译器要求用户
在程序中必须要捕获处理或声明抛出这些异
常,javac会对用户程序是否处理了检查型异
常进行检查,若未处理则编译不能通过
常见的检查型异常
?包 java.lang中声明的标准检查型异常
?包 java.io中声明的标准检查型异常
?包 java.net中声明的标准检查型异常
包 java.lang中声明的标准检查型异常
?ClassNotFoundException
?CloneNotSupportedException
IllegalAccessException
?InstantiationException
?InterruptedException
包 java.io中声明的标准检查型异常
?java.io,EOFException
?java.io,FileNotFoundException
?java.io.InterruptedIOException
?java.io.UTFDataFormatException
包 java.net中声明的标准检查型异常
?java.net.MalformedURLException
?java.net.ProtocolException
? java.net.SocketException
? java.net.UnknownHostException
?java.net.UnknownServiceException
运行时异常的例子
class ExceptionDomo2{
public static void main(String args[ ]){
int a[ ] = new int[-1];
}
}
检查型异常的例子
import java.io.*;
class ExceptionDomo1{
public static void main(String args[ ]){
String s = ("Hello!");
FileWriter f0 = new FileWriter("file1.txt");
f0.write(s);
f0.close();
}
}
异常的捕获处理和抛出
?一般来说,有两种对待异常的方式,
1、在方法内部捕获并处理该异常;
2、在本方法内不处理该异常,而是将异常抛
给方法的调用者,由调用者决定如何处理异
常。
捕获并处理异常
try
{
// 要监视(可能会出现异常)的程序块
}
catch (ExceptionType1 e)
{
// 对 ExceptionType1对象的处理
}
catch (ExceptionType2 e)
{
// 对 ExceptionType2对象的处理
}
finally
{
//最终处理语句
}
匹配的 catch子句
? Java运行时系统从上到下分别对每个 catch子句处理
的异常类型进行检测,直到找到与抛出的异常类型
相匹配的 catch子句为止。当且仅当出现下面三种情
况时,catch子句中的参数才被认为是与被抛出的异
常情况相匹配的,
? ①参数与被抛出的异常同属于一个类;
? ②参数是被抛出的异常的超类;
? ③参数是一个接口,被抛出的异常类实现了这个接
口。
抛出异常
?利用 try– catch –finally结构,可以对生成的异
常进行处理。但在有些情况下,如果在一个
方法中生成了一个异常,但是这一方法并不
确切地知道该如何对这一异常事件进行处理,
这时,该方法就可以声明抛弃异常,使得异
常对象从调用栈向后传播,直到有合适的方
法捕获它为止。
声明方法可能抛出的异常
?具体做法是在方法头中用 throws子句列出可
能抛出的异常类。例如,
public int read () throws IOException{
,....,
}
?在设计方法时应当在方法头部列出可能抛出
的检查型异常
用 throw语句抛出异常
?抛出异常首先要生成异常对象,生成异常对
象是通过 throw语句实现的。可以抛弃的异常
必须是 Throwable或其子类的实例。在方法体
内遇到异常时用 throw语句抛出异常对象。
?throw语句的格式为,
throw 异常类的对象引用
自定义异常
?用户自己的异常类必须声明为 Throwable的子
类。用户的异常类继承标准异常类中的任何
一个均可。常见的做法是:用户的异常类继
承 Exception类。这样 Java就会将定义的异常
类视为检查型异常,使自定义异常起到应有
的作用。自定义的异常类,一般只要声明两
个构造方法,一个是不用参数的,另一个以
字符串为参数。作为构造方法参数的字符串
应当反映异常的根源。
异常处理的例子
class MyException extends Exception{ //自定义异常类
MyException( ){ super( ); }
MyException(String s ){ super(s); }
}
class TryAndCatchA{
static int demoThrow(String s) throws MyException{ //在方法头中声明抛出异常
if (s.equals("welcome")){
System.out.println(s);
}
if (s.equals("bug")){
throw new MyException("a bug"); //在方法中抛出异常
}
return s.length( );
}
public static void main(String[ ] args){
for (int i=0; i<args.length; i++){
try{
demoThrow(args[i]);
System.out.println("------");
}
catch(MyException e){
System.err.println("demoThrow(\"" +args[i]+"\") 抛出了类型为 "+e.getClass()+",异常内容为 "+e.getMessage()+"的异
常,");
}
finally{ System.out.println("clean up..."); }
}
}
}
输入与输出包
?文件类
?流总介
?文件的输入输出流
?随机访问文件类
?产生文本文件
文件类
?java.io包中定义了一个 File类来专门处理文件,
并获取文件的有关信息。 Java语言中通过
File类来建立与磁盘文件的联系。
?File类的继承树是,
java.lang.Object
|
+--java.io.File
File类三种构造方法
?public File(String <pathname>)
?public File(String <path>,String <filename>)
?public File(File <directory>,String
<filename>)
File类的常用方法及其说明
方 法 说 明
public boolean exists( ) 判断文件 ( 或者目录 ) 是否存在 。
public boolean isDirectory( ) 判断该 File对象是否是目录 。
public boolean isFile( ) 判断该 File对象是否是文件 。
public boolean canRead( ) 判断文件是否可读 。
public boolean canWrite( ) 判断文件是否可写 。
public boolean isHidden( ) 测试当前对象是否是隐藏文件 ( 或目录 ) 。
public String getName( ) 返回文件 ( 或者目录 ) 的名字 。
public String getPath( ) 返回文件 ( 或者目录 ) 的路径 。
public String getAbsolutePath( ) 返回文件 ( 或者目录 ) 的绝对路径 。
public long length( ) 返回文件的长度 ( 以字节为单位 ) 。
public long lastModified( ) 获得文件最后一次修改的时间 。
public String[ ] list( ) 返回目录下的文件及子目录名列表 。
public boolean createNewFile( )
throws IOException 自动创建一个新的空文件, 要求该文件名未曾使用过 。
public boolean mkdir( ) 创建当前目录的子目录 。
public boolean delete( ) 删除当前文件或目录 。
public boolean renameTo (File dest) 为文件重新命名 。
public boolean setReadOnly( ) 将文件 ( 或者目录 ) 设置为只读 。
File类的例子
import java.io.*;
class TestFile{
public static void main(String[ ] args) throws Exception {
if (args.length != 1)
{ System.err.println("请输入一个参数! ");
System.exit(-1); }
File file = new File(args[0].trim()); //利用命令行参数创建 File 类的对象
if (file.exists()) { //如果文件对象存在
if(file.isFile()){ //如果是文件
System.out.println("File Name:"+file.getName());
System.out.println("Path:"+file.getPath());
System.out.println("Abs.Path:"+file.getAbsolutePath());
System.out.println("Writable:"+file.canWrite());
System.out.println("Readable:"+file.canRead());
System.out.println("Length:"+(file.length()) +"B"); }
else if (file.isDirectory()){ //如果是目录
String[ ] s = file.list();
System.out.println("There are "+s.length+" objects.");
for (int i=0; i<s.length; i++)
System.out.println(s[i]); }
}
else file.mkdir( ); //如果文件对象不存在
}
}
流总介
? 流可以被理解为一条“导管”。这条“导管”有两
个端口:一端与数据源(当输入数据时)或数据宿
(当输出数据时)相连,另一端与程序相连。
? 在与数据源或数据宿相连的端口,“导管”在读写
数据时能够应付数据源和数据宿的多样性,消化掉
因数据源和数据宿的多样性带来的数据读 /写的全部
复杂性;而在与程序相连的端口,“导管”提供了
输入 /输出的统一操作界面。
输入流的示意图
输出流的示意图
流的读 /写操作过程
读 (Reading)
操 作 功 能
打开数据流 创建流类对象, 并连接到输入源 。
读数据 从流中读入数据序 列 。
关闭数据流 关闭流, 释放相关的系统资源 。
写 (Writing)
操 作 功 能
打开数据流 创建流类对象, 并连接到输出目的地 。
写数据 从流中输出数据序列 。
关闭数据流 关闭流, 释放相关的系统资源 。
Java流总图
节点流总表
节点类型 字符流 字节流
Memory
(内存)
CharArrayReader
CharArrayWriter
ByteArrayInputStream
ByteArrayOutputStream
StringReader
StringWriter StringBufferInputStream
Pipe(管道) PipedReader PipedWriter PipedInputStream PipedOutputStream
File(文件) FileReader FileWriter FileInputStream FileOutputStream
文件的输入输出流
?节点流
?过滤流
节点流
?文件输入流 FileInputStream
?文件输出流 FileOutputStream
文件输入流 FileInputStream
?FileInputStream类的继承树为,
java.lang.Object
|
+--java.io.InputStream
|
+--java.io.FileInputStream
FileInputStream类常用的两种构造方法
?public FileInputStream(File file) throws
FileNotFoundException
?public FileInputStream(String name) throws
FileNotFoundException
FileInputStream有三种 read方法
?public int read() throws IOException
?public int read(byte[ ] b) throws IOException
?public int read(byte[ ] b,int off,int len)
throws IOException
FileInputStream类常用方法及其说明
方法 说明
public int available( ) throws IOException 返回可读入的字节数 。
public void close( ) throws IOException 关闭输入流, 并释放任何与该流有关的资源 。
public int read( ) 从输入流中读取一个字节的数据 。
public int read(byte[ ] b) 将数据读入到一个字节数组中 。
public int read(byte[ ] b,int off,int len) 将指定个数的数据读入到一个字节数 组中 。
public long skip(long n) throws IOException 跳过输入流上的 n个字节 。
文件输出流 FileOutputStream
?FileOutputStream类的继承树为,
java.lang.Object
|
+--java.io.OutputStream
|
+--java.io.FileOutputStream
FileOutputStream类提供的构造方法
?public FileOutputStream(File file) throws
IOException
?public FileOutputStream(String name)
throws FileNotFoundException
?public
FileOutputStream(String name,boolean app
end) throws FileNotFoundException
FileOutputStream类有三种 write方法
?public void write(int b) throws IOException
?public void write(byte[] b) throws
IOException
?public void write(byte[] b,int off,int len)
throws IOException
FileOutputStream类的常用方法及其说明
方法 说明
public void close( ) throws IOException 关闭输出流, 并释放任何与该流有关的资源 。
protected void finalize( ) throws IOException 当收集到无用信息时, 关闭该流 。
public void write(int b) 将指定的字节写到文件输出流中 。
public void write(byte[ ] b) 将一个字节数组中的数据写到输出流中 。
public void write(byte[ ] b,int off,int len) 将一个字节数组的部分数据写到输出流 中 。
个例
import java.io.*;
class FileInOut{
public static void main(String args[ ]) throws Exception{
System.out.println("从键盘输入文件内容,以回车结束, ");
char c;
StringBuffer buf = new StringBuffer();
try { while ((c = (char)System.in.read()) != '\n')
buf.append(c); //将输入的字符加到 buf中,直到遇见回车符
}
catch (java.io.IOException e) {
System.out.println("Error:"+e.toString()); }
byte b[]=buf.toString( ).trim( ).getBytes( ); //转换成一个字节数组
FileOutputStream f1 = new FileOutputStream("myfile1.txt");
f1.write(b); //将字节数组 b中的内容写到文件输出流中去
f1.close( );
FileInputStream f2 = new FileInputStream("myfile1.txt");
FileOutputStream f3 = new FileOutputStream("myfile2.txt");
int c2;
while ((c2 = f2.read()) != -1){ f3.write(c2); }
f2.close( );
f3.close( ); }
}
过滤流
?过滤流必须建立在节点流之上,对节点流中
的数据进行某些加工、处理,并提供一些友
好的方法供用户进行输入、输出操作以及流
控制
?介绍两种常用的过滤流
BufferedInputStream类
BufferedOutputStream类
BufferedInputStream类
? BufferedInputStream类的继承树为,
java.lang.Object
|
+--java.io.InputStream
|
+--java.io.FilterInputStream
|
+--java.io.BufferedInputStream
BufferedInputStream类提供的构造方法
?⑴ public
BufferedInputStream(InputStream in)
?⑵ public
BufferedInputStream(InputStream in,int size)
BufferedInputStream类的常用方法及
其说明
方法 说明
public int available( ) throws
IOException
返回可读入的字节数 。
public void close( ) throws
IOException
关闭输入流, 并释放任何与该流有关的资源 。
public void mark(int readlimit) 在输入流的当前位置做标记 。 流允许在标记位置无
效之前最多读入 readlimit个字节 。
public boolean markSupported( ) 测试该输入流是否支持 mark 和 reset 方法,
public void reset( ) throws
IOException
把流重定位在上一次标记的位置 。
public long skip(long n) throws
IOException
跳过输入流上的 n个字节 。
BufferedInputStream类的个例
import java.io.*;
class TryBufferin{
public static void main(String[ ] args){
if (args.length != 1)
{ System.err.println("请输入要从中读取数据的文件名! ");
System.exit(-1); }
try
{ FileInputStream in = new FileInputStream(args[0]);
//直接从命令行参数创建文件输入流
BufferedInputStream bufin = new BufferedInputStream(in,1024);
//在文件输入流的基础上创建缓冲输入流
System.out.println(bufin.available());
int count,half = bufin.available()/2;
bufin.skip(half);
if (bufin.markSupported()) { //判断该流是否支持 mark和 reset方法
int limit;
bufin.mark(limit = bufin.available( )); //在当前位置打标记
for (int i=0;i<limit;i++)
System.out.print((char)(bufin.read()));
System.out.println();
bufin.reset(); //把流重定位在上一次标记的位置
}
int c;
while((c=bufin.read())>=0)
System.out.print((char)c);
bufin.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
BufferedOutputStream类
? BufferedOutputStream类的继承树为,
java.lang.Object
|
+--java.io.OutputStream
|
+--java.io.FilterOutputStream
|
+--java.io.BufferedOutputStream
BufferedOutputStream类构造方法
?public
BufferedOutputStream(OutputStream out)
?public
BufferedOutputStream(OutputStream out,
int size)
BufferedOutputStream类的常用方法及其说明
方法 说明
public void flush() throws IOException 清空缓冲输出流, 将缓冲区中的所有内容强
行写到基层的节点流中去 。
public void write(int b) throws IOException 将指定的字节写到缓冲输出流中 。
public void write(byte[ ] b,int off,int len)
throws IOException
将一个字节数组中的部分数据写到缓冲输出
流中 。
public void close( ) throws IOException 关闭输出流, 并释放任何与该流有关的资源 。
BufferedOutputStream类的例子
import java.io.*;
class TryBufferout {
public static void main(String args[]) {
if (args.length!=1) { System.err.println("请输入要创建的文件名! ");
System.exit(-1); }
try {
FileOutputStream out=new FileOutputStream(args[0]);
BufferedOutputStream bufout=new BufferedOutputStream(out);
//创建文件输出流、缓冲输出流
String msg="Hello";
byte[] ob=msg.getBytes();
for (int i=0;i<1000;i++)
bufout.write(ob,0,ob.length); //将数组内容写到缓冲输出流中( 1000次)
bufout.flush(); //清空输出流缓冲
bufout.close();
}catch (IOException e) { //例外处理
e.printStackTrace(); }
}
}
随机访问文件类
? RandomAccessFile类的继承树是,
java.lang.Object
|
+--java.io.RandomAccessFile
? RandomAccessFile类提供了两种构造方法,
public RandomAccessFile(File file,String mode) throws
IOException
public RandomAccessFile(String name,String mode)
throws FileNotFoundException
RandomAccessFile对象的文件位置
指针遵循这样的规律
?新建 RandomAccessFile对象的文件位置指针
位于文件的开头处;
?每次读写操作之后,文件位置指针都相应后
移读写的字节数;
?可以通过 getFilePointer方法来获得文件位置
指针的位置,通过 seek方法来设置文件位置
指针的位置。
RandomAccessFile类的常用方法及其说明
方法 说明
public void close( ) 关闭随机访问文件流, 释放任何与其有关的资源 。
public long length( ) 返回文件的长度, 以字节为单位 。
public void seek(long pos) 将文件位置指针移到 pos指出的位置上 。
public long getFilePointer( ) 获得文件位置指针所指向的位置 ( 以字节为单位 ) 。
public int read( ) 从文件的当前位置开始读取一个字节 。
public int read(byte[ ] b) 把从文件中读取的数据放到一个字节数组中 。
public int read(byte[ ] b,int off,int len) 从文件中读取 len个字节, 从下标 off开始放到字节数组 b中 。
public final boolean readBoolean( ) 从文件中读取 1个字节, 返回对应的 boolean值 。 0 表示 false,其他值代表 true。
public final char readChar( ) 从文件中读取 2个字节, 返回 Unicode字符 。
public final int readInt( ) 从文件中读取 4个字节, 返回 int值 。
public final String readLine( ) 从当前位置开始, 到遇到行结束符或文件尾为止, 读取一行文本, 返回一个字符串 。
public void write(byte[ ] b) 将字节数组 b中的数据写到文件中 。
public void write(byte[] b,int off,int len) 将字节数组 b中从位置 off开始的共计 len个字节写到文件中去 。
public void write(int b) 将指定的数据写到文件中 。
public final void writeBoolean(boolean v) 将 boolean值按单字节的形式写到文件 。 true作为 (byte)1,false作为 (byte)0写出 。
public final void writeChar(int v) 将 char值按 2字节的形式写到文件中 。
public final void writeChars(String s) 将一个字符串按字符方式写到文件中 。
public final void writeInt(int v) 将 int值按 4字节的形式写到文件中 。
RandomAccessFile类的例子
import java.io.*;
class RandomAccessFileDemo{
public static void main(String args[ ]) throws IOException{
//以读写方式创建 RandomAccessFile对象
RandomAccessFile f = new RandomAccessFile("myfile","rw");
System.out.println("File Length:" + (f.length()) +"B");
System.out.println("File Pointer Position:" + f.getFilePointer( ));
//下面从文件末尾处开始写数据
f.seek(f.length( ));
f.writeBoolean(true);
f.writeBoolean(false);
f.writeChar('a');
f.writeChars("Hello!");
System.out.println("File Length:"+(f.length( )) +"B");
//下面从文件起始处开始读数据
f.seek(0);
System.out.println(f.readBoolean( ));
System.out.println(f.readBoolean( ));
while(f.getFilePointer() < f.length( ))
System.out.println(f.readLine( ));
f.close( ); }
}
产生文本文件
?PrintWriter类的继承树是,
java.lang.Object
|
+--java.io.Writer
|
+--java.io.PrintWriter
PrintWriter类的构造方法
? public PrintWriter(Writer out)
? public PrintWriter(Writer out,boolean autoFlush)
? public PrintWriter(OutputStream out)
? Public
PrintWriter(OutputStream out,boolean autoFlush)
PrintWriter类的常用方法及其说明
方法 说明
public void flush( ) 刷新输出缓冲区 。
public void close( ) 关闭当前流 。
public boolean checkError( ) 刷新流并检查其错误状态, 如果该打印流遇到错误则返回 true。
public void println ( ) 将行分隔符写入当前输出流 。 行分隔符是由系统属性 line.separator决定的 。
public void print (Object obj) 将对象 obj的字符串表示写入当前输出流 。 调用该方法等价于调用
print(obj.toString())。
public void println (Object obj) 相当于调用 print (Object obj)方法后再调用 println ()方法 。
public void print (type v) 将类型为 type的变量 v的值以字符串形式写入当前输出流 。 其中, type可以
是 char[],boolean,char,int,long,float和 double。
public void println (type v) 相当于调用 print (type v)方法后再调用 println ()方法 。
public void print(String s) 打印字符串 。
public void println(String x) 相当于调用 print(String s)方法后再调用 println ()方法 。
PrintWriter类产生文本文件的例子
import java.io.*;
class PrintWriterDemo{
public static void main(String[ ] args) throws IOException{
PrintWriter out=new PrintWriter(new FileWriter("myfile.out"));
String s = "使用打印流可以建立文本文件 ";
char[ ] c = {'自 ','然 ','对 ','数 ','的 ','底 ','='};
boolean b=true;
out.println(s);
out.print(c);
out.println(Math.E);
out.println(b);
out.close();
}
}
使用 DOS的输出重定向功能
import java.io.*;
class ChangeDir{
public static void main(String[ ] args){
String s = "使用打印流可以建立文本文件 ";
char[ ] c = {'自 ','然 ','对 ','数 ','的 ','底 ','='};
boolean b = true;
System.out.println(s);
System.out.print(c);
System.out.println(Math.E);
System.out.println(b);
}
}
其他常用资源简介
?java.net包
?java.util包
java.net包
?java.net包提供了一些类,可以用于实现网络
编程
?重点介绍其中两个较常用的类。
InetAddress类
URL类
InetAddress类
?InetAddress类描述了 IP地址,每个
InetAddress对象中包含了 IP地址、主机名等
信息。该类主要用来区分计算机网络中的不
同节点(即不同的计算机)并对其寻址。
?InetAddress类的继承树是,
java.lang.Object
|
+--java.net.InetAddress
InetAddress类的常用方法及其说明
方法 说明
public byte[ ] getAddress( ) 返回当前 InetAddress对象的 IP地址 。
public static InetAddress[ ]
getAllByName(String host)
throws UnknownHostException
返回代表给定主机名的所有 IP地址的 InetAddress数组 。
主机名可以是一个机器名, 例如 "java.sun.com",也
可以是一个描述该机 IP 地址的字符串,such as
"206.26.48.100"。
public static InetAddress
getByName(String host) throws
UnknownHostException
返回代表给定主机的 InetAddress对象 。 如果参数为
null,就代表本地主机 。
public String getHostAddress( ) 返回 IP 地址字符串 "%d.%d.%d.%d"( 点分十进制表
示 ) 。
public String getHostName( ) 返回对应该 IP地址的主机名 。
public static InetAddress getLocalHost()
throws UnknownHostException
返回代表本地主机的 IP地址的 InetAddress对象 。
InetAddress类的使用示例
import java.net.*;
public class TestIP{
public static void main(String argv[ ]) {
InetAddress Ip1 = null;
InetAddress Ip2 = null;
try {
Ip1 = InetAddress.getLocalHost( ); //返回本地主机的 IP地址
Ip2 = InetAddress.getByName("www.edu.cn"); //返回给定主机的 IP地址
}
catch(UnknownHostException e) {
System.out.println(e.toString( ));
}
System.out.println(Ip1);
System.out.println(Ip1.getHostAddress( ));
System.out.println(Ip1.getHostName( ));
System.out.println(Ip2);
System.out.println(Ip2.getHostAddress( ));
System.out.println(Ip2.getHostName( ));
}
}
URL类
?Java程序可以通过 java.net包中的 URL类方便
地访问 Internet网络上的资源。
?URL类的继承树是,
java.lang.Object
|
+--java.net.URL
URL的结构
?传输协议和资源名称,中间用,://”分隔开
?传输协议说明访问资源时使用的网络协议。
典型的传输协议有 http,ftp 等
?URL中协议名后面的部分叫 URI(统一资源标
识符 )。 URI中不能有空白,空格,回车符号,
如果需要则用编码表示
URL类提供了很多构造方法
?⑴ public URL(String spec) throws
MalformedURLException
?⑵ public URL(String protocol,String host,
String file) throws MalformedURLException
?⑶ public URL(URL context,String spec)
throws MalformedURLException
URL类的常用方法及其说明
方法 说明
public final Object getContent( ) throws
IOException
返回该 URL的内容 。 这个方法相当于,
openConnection().getContent()
public String getProtocol( ) 返回该 URL中的传输协议名 。
public String getHost( ) 返回该 URL中的主机名 。
public String getFile( ) 返回该 URL中的文件名 。
public int getPort( ) 返回该 URL中的端口号, 如果一个 URL地址没有端口号,
返回值为 -1。
public String getRef( ) 返回 URL中的参考点, 如果一个 URL地址没有参考点,
返回值为 null。
public final InputStream openStream() throws
IOException
打开到当前 URL的连接并返回一个 InputStream用于从该连
接中读取数据 。 这个方法相当于,
openConnection().getInputStream()
URL类的使用示例
import java.net.*;
import java.io.*;
class URL_PageScan{
public static void main(String args[ ]){
System.out.println("Working...");
if(args.length != 1)
{ System.out.println("请传递一个参数,URL地址 ");
System.exit(0);
}
URL u1 = null;
try{ u1 = new URL(args[0]);
}
catch(MalformedURLException e)
{ System.out.println("Bad URL:" + u1);
}
StringBuffer page = new StringBuffer( );
try{
InputStream in = u1.openStream( );
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
int data;
while((data=reader.read( )) != -1)
page.append((char)data);
}
catch(IOException e)
{
System.out.println("I/O error"+e.getMessage( ));
} //计算 "HREF"出现的次数
int refCount = 0;
for(int i=4; i<page.length(); i++)
if(page.substring(i-4,i).equalsIgnoreCase("HREF"))
refCount++;
System.out.println("Pages referenced:"+refCount);
}
}
java.util包
?java.util包可以看作是 java.lang包的补充,它
包括了一些实用工具。利用这些实用工具,
可以对程序进行更高级的控制
?重点介绍其中两个较常用的类
?Calendar类
?Random类
Calendar类
? Calendar类是一个抽象的基类,用来在一个 Date对
象(在毫秒级上描述了一个精确的时刻)和一系列
的整数字段(比如 YEAR,MONTH,DAY,HOUR等
等)之间进行转换。
? Calendar类的继承树是,
java.lang.Object
|
+--java.util.Calendar
Calendar类的常用字段及其说明
字段 说明
public static final int AM_PM 指出当前时间是在正午之前还是之后 。 为 0指上午, 为 1指下午 。
public static final int HOUR 指出上午或下午的小时 。 它用的是 12小时制 。
public static final int HOUR_OF_DAY 指出上午或下午的小时 。 它用的是 24小时制 。
public static final int MINUTE 指出小时内的分钟 。
public static final int SECOND 指出分钟内的秒数 。
public static final int MILLISECOND 指出秒内的毫秒数 。
public static final int DAY_OF_WEEK 指出是当前星期的第几天, 第 1天从星期日算起 。
public static final int
DAY_OF_WEEK_IN_MONTH
指出当前日子是在当前月内的第几周 。 它和 DAY_OF_WEEK
一起, 唯一确定了某月的某一天 。
public static final int DAY_OF_MONTH 指出是当前月的第几天, 即几号 。
public static final int DAY_OF_YEAR 指出是当前年的第几天, 从 1月 1号算起 。
public static final int WEEK_OF_MONTH 指出在当前月中是第几个星期 。
public static final int WEEK_OF_YEAR 指出在当前年中是第几个星期 。
public static final int MONTH 指出月份 。
public static final int YEAR 指出年份 。
Calendar类的常用方法及其说明
方法 说明
public final int get(int field) 获得指定时间字段的值 。
public static Calendar getInstance( ) 用默认的时区和场所生成一个 calendar对象 。
public final void set(int field,
int value)
将指定时间字段设为指定的值 。
public abstract void add(int field,
int amount)
将指定的值加到指定的时间字段上去 。 例 如,
add(Calendar.DATE,-5),
Calendar类的例子, 显示当前日期和时间
import java.util.*;
class CalendarDemo{
public static void main(String args[ ]){
Calendar now = Calendar.getInstance();
int ampm = now.get(Calendar.AM_PM );
int hour = now.get(Calendar.HOUR_OF_DAY);
int hour2 = now.get(Calendar.HOUR);
int minute = now.get(Calendar.MINUTE);
int month = now.get(Calendar.MONTH); //注意,Calendar类是用 0~11来表示月份的,
int day = now.get(Calendar.DAY_OF_MONTH);
int day2 = now.get(Calendar.DAY_OF_WEEK);
int day3 = now.get(Calendar.DAY_OF_WEEK_IN_MONTH);
int day4 = now.get(Calendar.DAY_OF_YEAR);
int year = now.get(Calendar.YEAR);
int week = now.get(Calendar.WEEK_OF_MONTH);
int week2 = now.get(Calendar.WEEK_OF_YEAR);
System.out.println("今天是,");
System.out.println(month + 1 + "月 "+ day + "日 ");
System.out.println(month + 1 +"月第 " + week + "周第 " + day2 + "天 ");
System.out.println(month + 1 +"月第 "+day3 + "周第 " + day2 + "天 ");
System.out.println("今年的第 "+day4+"天 ");
System.out.println("今年的第 " + week2 + "周第 " + day2 + "天 ");
System.out.println("时间是,");
System.out.println(hour + "点 " + minute + "分 ");
System.out.print(ampm!=1?"上午 ":"下午 ");
System.out.println(hour2 + "点 " + minute + "分 ");
if(hour < 12)
System.out.println("Good morning!");
else if(hour < 17)
System.out.println("Good afternoon!");
else
System.out.println("Good evening!");
System.out.print("It's");
if(minute != 0){
System.out.print(" "+minute+" ");
System.out.print((minute!=1)? "minutes", "minute");
System.out.print(" past ");
}
System.out.print((hour > 12)? (hour-12), hour);
System.out.print(" o'clock on ");
String monthName[ ]={"January","February","March","April",
"May","June","July","August","September","October","November","December"};
System.out.print(monthName[month]);
System.out.println(" "+day+","+year+"."); }
}
Random类
? Random类的对象用于产生一个伪随机数。
? Random类的继承树是,
java.lang.Object
|
+--java.util.Random
? Random类提供了两种构造方法,
⑴ public Random()
⑵ public Random(long seed)
Random类的常用方法及其说明
方法 说明
public int nextInt( ) 返回下一个随机整数 ( 带符号 ) 。
public double nextDouble( ) 返回一个大于等于 0.0且小于 1.0的随机数 。
public boolean nextBoolean( ) 返回下一个随机的布尔值 。
public void setSeed(long seed) 用给定参数来设置当前随机数发生器的种子 。
Random类的例子
import java.util.*;
class RandomDemo{
public static void main(String args[ ]){
Random rd = new Random();
int[ ] fre = new int[6]; //记录相同的数出现的次数
int rdGet; //取得随机数
for(int i=0; i<1000; i++) {
rdGet = Math.abs(rd.nextInt( )) % 6 + 1; //产生 1~6之间的随机数
switch(rdGet)
{ case 1:fre[0]++; break;
case 2:fre[1]++; break;
case 3:fre[2]++; break;
case 4:fre[3]++; break;
case 5:fre[4]++; break;
case 6:fre[5]++; break; }
}
for(int j=0;j<fre.length;j++)
System.out.println((j+1)+"出现的次数,"+fre[j]+"; 出现的比率,"+fre[j]/10.0+"%");
}
}
习题