Java 输入输出(含部分答案) 下载本文

Java输入输出

知识点:

1、文件和流的操作,理解字节流和字符流的概念 2、异常处理的概念,自定义异常类

一、选择题

1、如果一个程序段中有多个catch,则程序会按如下哪种情况执行? ( )

A)找到合适的例外类型后继续执行后面的catch B)找到每个符合条件的catch都执行一次

C)找到合适的例外类型后就不再执行后面的catch D)对每个catch都执行一次

2、程序员将可能发生异常的代码放在( )块中,后面紧跟着一个或多个( )块。

A) catch、try B) try、catch

C) try、exception D) exception、try

3、在Java语言中,在程序运行时会自动检查数组的下标是否越界,如果越界,会抛掷下面的异常( )

A) SQLException B) IOException C) ArrayIndexOutOfBoundsExcetion D) SecurityManager

4、在Java中,关于捕获异常的语法try-catch-finally的下列描述哪些正确?( ) A) try-catch必须配对使用 B) try可以单独使用

C) try-finally必须配对使用 D) 在try-catch后如果定义了finally,则finally肯定会执行

5、给定下面的代码片断:

public class Animal{ public void Cat(){ try{

Method(); }

catch(ArrayIndexOutBoundsException e) {System.out.println(\ catch(Exception e)

{System.out.println(\ finally

{System.out.println(\ }

public void Method() { //... }

public static void main(String[] args) {

Animal.Ani=new Animal (); Ani. Cat (); } }

如果函数method正常运行并返回,会显示下面的哪些信息?( ) A) Hello World B) Exception1

1

C) Exception2 D) Hello World!!

6、如果下列的方法能够正常运行,在控制台上将显示什么?( )

public void example(){ try{

unsafe();

System.out.println(\ }

catch(SafeException e) {

System.out.println(\ }

finally{System.out.println(\ System.out.println(\}

A) Test 1 B) Test 2 C) Test 3 D) Test 4

7、以下哪一项不是File类的功能: ( )

A) 创建文件 B) 创建目录 C) 删除文件 D) 拷贝文件

2、下面哪个不是InputStream类中的方法: ( ) A) int read(byte[]) B) void flush() C) void close() D) int available() 8、构造BufferedInputStream的合适参数是哪个?

A) BufferedInputStream B) BufferedOutputStream C) FileInputStream D) FileOuterStream E) File 9、要从文件\file.dat\文件中读出第10个字节到变量C中,下列哪个方法适合? ( )

A) FileInputStream in=new FileInputStream(\c=in.read();

B) FileInputStream in=new FileInputStream(\c=in.read();

C) FileInputStream in=new FileInputStream(\D) RandomAccessFile in=new RandomAccessFile(\

int c=in.readByte();

10、以下程序发生什么异常? class A { int x;

public static void main { A x;

System.out.println(x.x); } }

A. IOException

B. InterruptException C. NullPointerException D. DataFormatException 11、设有如下方法: public void test() { try {

2

oneMethod();

System.out.println(\

} catch (ArrayIndexOutOfBoundsException e) { System.out.println(\ } catch(Exception e) {

System.out.println(\ } finally {

System.out.println(\ } }

如果oneMethod正常运行,则输出结果中有哪些? A. condition 1 B. condition 2 C. condition 3 D. finally

12、设有如下代码: public void fun () { int i; try {

i=System.in.read ();

System.out.println(\ } catch (IOException e) {

System.out.println(\ } finally {

System.out.println(\ }

System.out.println(\}

如果有一个IOException发生, 则输出有哪些? A. Location 1 B. Location 2 C. Location 3 D. Location 4

13、设有如下代码:

1 String s = null;

2 if ( s != null & s.length() > 0)

3 System.out.println(\ 4 if ( s != null && s.length() > 0)

5 System.out.println(\ 6 if ( s != null || s.length() > 0)

7 System.out.println(\ 8 if ( s != null | s.length() > 0)

9 System.out.println(\以下行中哪些会产生空指针异常。 A. 2,4 B. 6,8 C. 2,4,6,8 D. 2,6,8

3

14、类Test1、Test2定义如下: 1.public class Test1 {

2. public float aMethod(float a,float b) throws IOException { 3. } 4. }

5. public class Test2 extends Test1{ 6. 7. }

将以下哪种方法插入行6是不合法的。

A、float aMethod(float a,float b){ }

B、public int aMethod(int a,int b)throws Exception{ } C、public float aMethod(float p,float q){ }

D、public int aMethod(int a,int b)throws IOException{ } 15、设有如下代码: try {

tryThis(); return;

} catch (IOException x1) {

System.out.println(\ return;

} catch (Exception x2) {

System.out.println(\ return; } finally {

System.out.println(\ }

如果tryThis() 抛出 NumberFormatException,则输出结果是? A. 无输出

B. \后跟 \C. \后跟 \D. \E. \

16、以下哪个是RandomAccessFile文件的构造方法: A.RandomAccessFile(\B.RandomAccessFile(\C.RandomAccessFile(\D.RandomAccessFile(\17、设有如下代码: import java.io.*; public class Th{

public static void main(String argv[]){ Th t = new Th(); t.amethod(); }

public void amethod(){ try{

ioCall();

}catch(IOException ioe){} }

4

}

以下哪个最有可能是ioCall方法的方法体?

A. public void ioCall () throws IOException{

DataInputStream din = new DataInputStream(System.in); din.readChar(); }

B. public void ioCall () throw IOException{

DataInputStream din = new DataInputStream(System.in); din.readChar(); }

C. public void ioCall (){

DataInputStream din = new DataInputStream(System.in); din.readChar(); }

D. public void ioCall throws IOException(){

DataInputStream din = new DataInputStream(System.in); din.readChar(); }

18、当前目录不存在名为Hello.txt的文件,执行下面代码的输出结果为? import java.io.*; public class Mine{

public static void main(String argv[]){ Mine m=new Mine( );

System.out.println(m.amethod()); }

public int amethod(){ try{

FileInputStream file=new FileInputStream(\ }

catch(FileNotFoundException e){

System.out.print(\ return -1; }

catch(IOException e){

System.out.print(\ }

return 0; } }

A. No such file found B. No such file found-1

C. No such file foundDoing finally-1 D. 0

19、使用哪个类可创建目录?

A. File B. DataOutput C. Directory D. FileDescriptor E. FileOutputStream

20、假设raf是一个随机访问文件,以下语句的编译和运行结果为?raf.seek( raf.length() ); A.代码不能编译.

5

B.会出现IOException

C.文件指针将定位到文件的最后一个字符之前 D.文件指针将定位到文件的最后一个字符

21、以下哪些是FileOutputStream 构造方法的合法形式? A. FileOutputStream( FileDescriptor fd ) B. FileOutputStream( String n, boolean a ) C. FileOutputStream( boolean a ) D. FileOutputStream()

E. FileOutputStream( File f ) 22、以下哪个能编译通过?

A.File f = new File(\

B. DataInputStream d = new DataInputStream(System.in);

C. OutputStreamWriter o = new OutputStreamWriter(System.out); D. RandomAccessFile r = new RandomAccessFile(\23、以下程序的调试结果为: import java.io.*; class Base{

public void amethod()throws FileNotFoundException{} }

public class ExcepDemo extends Base{

public static void main(String argv[]){ ExcepDemo e = new ExcepDemo(); }

public void amethod(){} protected ExcepDemo(){ try{

DataInputStream din = new DataInputStream(System.in); System.out.println(\ din.readByte();

System.out.println(\ this.amethod();

}catch(IOException ioe) { } } }

A. 由于构造方法为protected导致编译出错 B. 由于amethod方法未声明异常导致编译出错 C. 由于amethod方法未声明异常导致运行错误

D. 输出显示 \,击键后显示\

24、下列描述中不属于 Java异常处理机制优点的一项是( D )。 A、把错误处理代码从正常代码中分离出来 B、按错误类型和差别分组 C、对无法预测的错误的捕获和处理 D、能够处理任何类型的错误 25、下列方法中哪一个不能用于获取异常信息( C )?

A、toString ( ) B、getMessage( ) C、drawline( ) printStackTrace()

26、下列描述中,哪一项不属于finally语句应陔执行的功能( C )?

A、释放资源 B、关闭文件 C、分配资源 D、关闭数据库27、下列关于RuntimeException的说法中正确的一个项( D )。 A、此异常默认可以被除了main( )方法之外的任何方法抛出 B、它没有被强迫处理,因此也不会被main( )处理

6

D、 C、这种异常属于检测异常

D、从jdk的docs可以了解都有哪些异常属于此类

28、下列关于异常处理原则的说法中错误的一项是( )。 A、修正问题,并再次调用引发异常的方法

B、暂时解决问题,不再尝试执行该方法,转而继续程序的执行 C、用一个可替代的结果替换方法本来应该得出的值 D、进行一些工作,然后把同一异常重掷到较低层

29、下列关于异常使用原则的说法中错误的一项是( )。 A、处理本异常,然后再把另一个不同异常重掷到较低层 B、中止程序,不让程序继续向下运行

C、使问题简化,不用花很多时间在跟踪错误上 D、让程序更安全

30、下列描述中,正确的一项是( )。

A、当异常被抛出时,可能产生由于没有与之匹配的catch子句而过早地返回的情况 B、一个try代码段必须和一个catch代码段相对应 C、catch(Exception e)不能捕获异常抛出的任何类型

D、非GUI程序产生异常时,若没有合适的异常处理与之匹配,则程序将恢复正常的运行 31、下列选项中,哪一个属于输出流?( )

A、从打印机流向控制器的数据流 B、从键盘流向内存的数据流 C、从内存流向控制器的数据流 D、从内存流向网络的数据流 32、下列哪一个类属于java.util.jar包?( ) A、GZIPlnputStream B、ZipInputStream C、JarlnputStream D、InflaterInputstream 33、Fileoutputstream类的父类是( )。

A、File B、FileOutput C、OutputStream D、InputStream 34、下列说法中,错误的一项是( )。

A、Java系统的标准输入对象是System.in B、打开一个文件时不可能产生IOException C、使用File对象可以判断一个文件是否存在 D、使用File对象可以判断一个目录是否存在

35、下列哪一个是Pattern类的方法?( )

A、matches() B、find() C、start() D、end() 36、下列哪一个类实现了线程组?( )

A、java.lang.Objict B、java.1ang.ThreadGroup C、Java.1ang.Thread D、java.1ang.Runnable 37、要实现完全定制串行化,串行化类必须实现的接口是( )

A、Serializable B、Runnable C、Thread D、Extenalizable

38、File类中的( )方法可以用来判断文件或目录是否存在。(选择一项)

A. exist(); B. exists(); C. fileExist(); D. fileExists(); 【解析】B

39、File类中的( )方法可以用来获取文件的大小。(选择一项)

a) length() b) size()

c) getLength() d) getSize() 【解析】A

7

40、文本文件的读写过程中,需要处理下列( )异常。(选择一项)

a) ClassNotFoundException b) IOException c) SQLException d) RemoteException 【解析】B

41、字符流是以( )传输数据的。(选择一项)

a) 1个字节 b) 8位字符

c) 16位Unicode字符 d) 1比特 【解析】C

42、( )方法可以用来清空流。(选择一项)

a) void release() b) void close() c) void Remove() d) void flush 【解析】D

43、对于异常处理语句try?catch?finally,下面哪个说法是正确的?( C ) A) 如果有多个catch语句,对所有的catch都执行一次

B) 如果有多个catch语句,对每个符合条件的catch都执行一次 C) 找到合适的异常类型后就不再执行后面的catch D) 任何情况下,finally部分都会被执行一次

44、对于异常处理语句try?catch,下面那句话不正确? ( A )

A、一个符合条件的catch的处理语句中没有break语句,则执行后会继续执行后续catch B、不管有没有捕获异常,finally部分都会被执行 C、找到合适的异常类型后就不再执行后面的catch D、应该先处理子异常类,再处理父异常类。

45、用文件字节输出流对文件进行写操作时,需要先创建文件输出流对象,文件输出数据流的构造方法是 public FileOutputStream(String name,Boolean append) throws FileNotFoundException,当参数append的值为true时,表示 ( B )

A、创建一个新文件

B、在原文件的尾部添加数据 C、覆盖原文件的内容

D、在原文件的指定位置添加数据

46、下列哪种操作不会抛出异常?( B ) A) 浮点数除0 B) 浮点数乘0

C) 打开不存在的文件 D) 用负数索引访问数组 47、下面的程序段的功能是( A )。

File file1=new File(\ file1.mkdir();

A)在当前目录下生成子目录:\\xxx\\yyy B)生成目录: e:\\xxx\\yyy C)在当前目录下生成文件xxx.yyy D)以上说法都不对

48、对于异常处理语句try?catch?finally,下面哪个说法是正确的? ( C ) A) 如果有多个catch语句,对所有的catch都执行一次

B) 如果有多个catch语句,对每个符合条件的catch都执行一次 C) 找到合适的异常类型后就不再执行后面的catch D) 任何情况下,finally部分都会被执行一次

8

49、如果一个程序段中有多个catch,则程序会按如下哪种情况执行? ( ) A) 找到合适的异常类型后继续执行后面的catch B) 找到每个符合条件的catch都执行一次

C) 找到合适的异常类型后就不再执行后面的catch D) 对每个catch都执行一次

50、下列哪一段代码能够删除文件file.txt A、File f=new File(“file.txt”); f.delete();

B、RandomAccessFile f=new RandomAccessFile(“file.txt”,”rw”); f.delete();

C、FileOutputStream f=new FileOutputStream(“file.txt”); f.remove();

D、File f=new File(“file.txt”); File.delete(f);

51、下面哪一个流属于过滤流 A、InputStream B、FileInputStream C、DataInputStream D、FileReader

52、设有以下程序段 class TestException {

public static void main(String [] args) {

try{

return; }finally{

System.out.println(\ } } }

程序编译并执行,其结果将是 A、程序执行,但没有任何输出 B、程序输出finally

C、程序编译时出错,提示缺少catch

D、程序编译时出错,提示finally语句无法访问到。 53、下面哪一种流可以用来输入字符 A、InputStream B、OutputStream

C、InputStreamReader D、BufferedInputStream

二、填空题

1、数据越界抛出的异常类是 ,整数除零抛出的异常类是 ,算术溢出抛出的异常类是 。

2、写出4个常见的异常例子: 、 、 和 。重新抛出一个异常用 语句。 3、创建文件(c:\\test.txt)对象的语句是 ,DataInputStream对象提供 方法可以按行读取文件内容。

9

4、异常处理在内存中采用_ 堆栈 ____机制。

5、Java语言机制的优点主要有:把错误处理代码从___ 常规 ___中分离出来;按错误类

型和差别分组;对无法预测的错误的捕获和处理;克服了传统方法的错误信息有限的问题;把错误传播给调用堆栈。

6、用户定义异常是通过扩展__ Exception __类及_ throwable 类来刨建的。

7、在Java编程语言中,用_ try __, catch ___,__ finally ___语句来处理异常。

8、由于系统不能识别和创建用户_ 自定义的异常 ___,所以需要在程序的合适位置

创建__自定义异常对象 ___,并使用throw语句将该新异常对象抛出。

9、Java语言的异常处理机制中__ catch ___子句或_ finally ____子句可省略,但二者不能同时省略。

10、若抛出的异常类的对象不在catch之列,或者catch子句中包含__ 异常对象 ___

语句,则执行finally子句中的代码之后返_ 异常处理 ___。

11、使用管道流的时候,需要明确管道的__ ___是管道的接收方,而管道的__ ___

是管道的发送方。

12、输入输出在计箅机中有两个主要作用:_ 采集数据 ___和_ 提供数据处理结果 。

13、ByteArraylnputStream以__ 字节数组 _作为输入流。

14、所有的输出过滤流都是抽象类_ FilterOutputStream ____的子类。 15、字符输入流BufferedReader使用了__ PrintStream ____技术。 16、CharArrayWrlter类写入的是一个内部的__ 字符数组 ___。

17、stringWriter类写入的是一个内部的___ StringBuffer __。

18、流类处理的是文件的_ 内容 ___,而Flie类处理的是文件在磁盘上的_ 存储 ___。

19、从DataInlputStream对象dis的当前位置处读取一个字符串保存在变量str中的语句是 _

20、用FileInputStream类创建文件(c:\\test.txt)对象的语句是 ,DataInputStream对象提供 方法可以按行读取文件内容。 21、写出三个常见Exception的子类: 、 和 。

22、阅读下面的程序,写出带划线语句或注释,并写出该程序的作用: import java.io.*; public class Test {

public static void main(String args[]) { scanFiles(\ }

public static void scanFiles(String path) { if (path == null) return;

File f = new File(path); // if (!f.exists()) return;

if (f.isFile()) // System.out.println(f.getAbsolutePath()); else {

File dir[] = f.listFiles(); for (int i = 0; i < dir.length; i++)

scanFiles(dir[i].getAbsolutePath());//

10

} } } /*

创建path的File对象,对象引用名为f 判断f的对象是否为文件 递归调用scanFiles方法

该程序的作用是扫描C盘下所有的文件,并将文件的路径打印 */

23、阅读下面的程序Test.java,先填写空格的内容,然后写出运行结果:

1) import java.io.*; 2) public class Test{

3) public static void main(String argv[]){

4) ; //创建Test对象,对象名为t 5) System.out.println(t.fliton()); 6) }

7) public int fliton(){ 8) try{

//第9行的含义是: 9) FileInputStream din = new FileInputStream(\10) din.read();

11) }catch(IOException ioe){ //第11行的含义是: 12) System.out.println(\13) return -1; 14) }

15) finally{

16) System.out.println(\17) }

18) return 0; 19) } 20) }

如果文件test.txt与Test.java在同一个目录下,test.txt中仅有一行字符串“hello world!”,运行结果是什么? /*

Test t=new Test();

创建test.txt文件的FileInputStream对象,对象引用名为din 运行结果是: two 0 */

24、假设有一个文件为c:\\test.txt,则用FileInputStream类创建该文件引用对象fin的语句是 _____ ,用BufferedReader类去读取该文件需创建引用对象br的语句是____________________________________________________。 // FileInputStream fin=new FileInputStream(\

BufferedReader br=new BufferedReader(new FileReader(\

三、简答题

1、仔细阅读下面的程序,写出程序的执行顺序(写出编号):

11

public class UsingExceptions {

public static void main( String args[] ) {

try{

method1(); // 1 }catch(Exception e){

System.err.println(e.getMessage()); // 2 }

finally{

System.out.println(\ } }

public static void method1() throws Exception {

method2(); //4 }

public static void method2() throws Exception {

method3(); //5 }

public static void method3() throws Exception {

throw new Exception( \ } }

2、阅读下面的程序Test.java,先填写空格的内容,然后写出运行结果:

import java.io.*; public class Test{

public static void main(String argv[]){

; //创建Test对象,对象名为t System.out.println(t.fliton()); }

public int fliton(){ try{

//第9行的含义是: FileInputStream din = new FileInputStream(\ din.read();

}catch(IOException ioe){ //第11行的含义是: System.out.println(\ return -1; }

finally{

System.out.println(\ }

return 0; } }

如果文件test.txt与Test.java在同一个目录下,test.txt中仅有一行字符串“hello world!”,运行结果是什么?

12

3、阅读下面的程序Test.java:

import java.io.*; public class Test{

public static void main(String argv[]){ Test t = new Test();

System.out.println(t.fliton()); }

public int fliton(){ try{

FileInputStream din = new FileInputStream(\ din.read();

}catch(IOException ioe){

System.out.println(\ return -1; }

finally{

System.out.println(\ }

return 0; } }

如果文件test.txt与Test.java在同一个目录下,test.txt中仅有一行字符串“hello world!”,上面的程序编译是否成功?如果编译出错,指出哪行出错,并说明理由;如果编译正确,运行结果是什么?

4、阅读下面的程序TestMonth.java: public class TestMonth{

public static void main(String []args){

try{

int month=Integer.parseInt(args[0]); if(month<0||month>12){

throw new ArithmeticException(\没有\月份!\}

System.out.println(\您输入的月份为\月份\}catch(ArrayIndexOutOfBoundsException e){

System.out.println(\请输入月份!\}catch(ArithmeticException e){

System.out.println(\捕获ArithmeticException异常\System.out.println(e.toString()); } } }

已知ArrayIndexOutOfBoundsException和ArithmeticException都是java.lang.*下的异常类,编译TestMonth.java后,用java TestMonth 13的运行结果是什么? 参考答案:

捕获ArithmeticException异常

13

java.lang.ArithmeticException:没有13月份! 5、运行时异常与一般异常有何异同?

异常表示程序运行过程中可能出现的非正常状态,运行时异常表示虚拟机的通常操作中可能遇到的异常,是一种常见运行错误。java编译器要求方法必须声明抛出可能发生的非运行时异常,但是并不要求必须声明抛出未被捕获的运行时异常。 6、Java中的异常处理机制的简单原理和应用。

当JAVA程序违反了JAVA的语义规则时,JAVA虚拟机就会将发生的错误表示为一个异常。违反语义规则包括2种情况 一种是JAVA类库内置的语义检查。例如数组下标越界,会引发IndexOutOfBoundsException;访问null的对象时会引发NullPointerException。另一种情况就是JAVA允许程序员扩展这种语义检查,程序员可以创建自己的异常,并自由选择在何时用throw关键字引发异常。所有的异常都是java.lang.Thowable的子类。

7、JAVA语言如何进行异常处理,关键字:throws,throw,try,catch,finally分别代表什么意义?在try块中可以抛出异常吗?

Java通过面向对象的方法进行异常处理,把各种不同的异常进行分类,并提供了良好的接口

在Java中,每个异常都是一个对象,它是Throwable类或其它子类的实例。当一个方法出现异常后便抛出一个异常对象,该对象中包含有异常信息, 调用这个对象的方法可以捕获到这个异常并进行处理。

Java的异常处理是通过5个关键词来实现的:try、catch、throw、throws和finally。 一般情况下是用try来执行一段程序,如果出现异常,系统会抛出(throws)一个异常, 这时候你可以通过它的类型来捕捉(catch)它,或最后(finally)由缺省处理器来处理。

用try来指定一块预防所有“异常”的程序。紧跟在try程序后面,应包含一个catch子句来指定你想要捕捉的“异常”的类型。 throw语句用来明确地抛出一个“异常”。throws用来标明一个成员函数可能抛出的各种“异常”

Finally为确保一段代码不管发生什么“异常”都被执行一段代码。可以在一个成员函数调用的外面写一个try语句,

时间是李寻欢手里的飞刀,当你突然感觉到它的存在,它已经结实的钉在你喉咙上了。 在这个成员函数内部写另一个try语句保护其他代码。每当遇到一个try语句,“异常”的框架就放到堆栈上面,直到所有的try语句都完成。如果下一级的try语句没有对某种“异常”进行处理,堆栈就会展开,直到遇到有处理这种“异常”的try语句。 8、java中有几种类型的流?JDK为每种类型的流提供了一些抽象类以供继承,请说出他们分别是哪些类?

字节流,字符流。字节流继承于InputStream \\ OutputStream,字符流继承于InputStreamReader \\ OutputStreamWriter。在java.io包中还有许多其他的流,主要是为了提高性能和使用方便。

9、什么是java序列化,如何实现java序列化?

序列化就是一种用来处理对象流的机制,所谓对象流也就是将对象的内容进行流化。 可以对流化后的对象进行读写操作,也可将流化后的对象传输于网络之间。 序列化是为了解决在对对象流进行读写操作时所引发的问题。

序列化的实现:将需要被序列化的类实现Serializable接口,该接口没有需要实现的方法,

implements Serializable只是为了标注该对象是可被序列化的, 然后使用一个输出流(如:FileOutputStream)来构造一个ObjectOutputStream(对象流)对象,

接着,使用ObjectOutputStream对象的writeObject(Object obj)方法就可以将参数为obj的对象写出(即保存其状态),

14

要恢复的话则用输入流。 10、在Java中,以下的异常:java.lang.Excetion,java.lang.RuntimeException,java.lang.Error有什么区别?

Error类对象由Java虚拟机生成并抛出,Exception类对象由应用程序处理或抛出 error表示恢复不是不可能但很困难的情况下的一种严重问题。比如说内存溢出。不可能指望程序能处理这样的情况。

Error表示系统级的错误和程序不必处理的异常,

RuntimeException是Exception的子类,一般来说该异常是程序在运行时抛出这种错误编译是无法捕捉的,如果在程序中不加处理,在程序运行就会产生并上缴给JVM处理。

异常表示程序运行过程中可能出现的非正常状态,运行时异常表示虚拟机的通常操作中可能遇到的异常,是一种常见运行错误。Java编译器要求方法必须声明抛出可能发生的非运行时异常同,但是并不要求必须声明抛出未被捕获的运行时异常。

exception表示一种设计或实现问题。也就是说,它表示如果程序运行正常,从不会发生的情况

Exception表示需要捕捉或者需要程序进行处理的异常。 11.Java中异常处理机制、事件机制?

异常处理机制:

Java通过面向对象的方法进行异常处理,把各种不同的异常进行分类,并提供了良好的接口。这种机制为复杂程序提供了强有力的控制方式。同时这些异常代码与“常规”代码分离,增强了程序的可读性,编写程序时也显得更灵活。异常处理还有一个好处是在你不能确定 和处理异常时,你可以不处理,而把问题提交上去。另一方面,异常处理机制便利错误处理代码更有条理,更便于维护。

事件机制:

事件从事件源到监听者的传递是通过对目标监听者对象的Java方法调用进行的。对每个明确的事件的发生,都相应地定义一个明确的Java方法。这些方法都集中定义在事件监听者(EventListener)接口中,这个接口要继承java.util.EventLlistener。实现了事件监听者接口中一些或全部方法的类就是事件监听者。伴随着事件的发生,相应的状态通常都封装在事件状态对象中,该对象必须继承自java.util.EventObject。事件状态对象作为单参数传递给应响应该事件的监听者方法中。发出某种特定事件的事件源的标识是:遵从规定的设计格式为事件监听者定义注册方法,并接受对指定事件监听者接口实例的引用。有时,事件监听者不能直接实现事件监听者接口,或者还有其它和额外动作时,就要在一个源与其它一个或多个监听者之间插入一个事件适配器类的实例,来建立它们之间的联系。

四、编程题

1、编写一个java课的成绩统计程序,从键盘输入学生姓名和成绩,程序按成绩排出名次,并统计出最高分、最低分、平均分。学生的个数在程序运行前是未知数。

2、编写一个文件拷贝的程序,将文件C:\\test1.txt的内容拷贝到C:\\test2.txt中。 参考代码如下: import java.io.*;

public class CopyFile {

public static void main(String args[]){ FileInputStream from = null; FileOutputStream to = null; try {

from = new FileInputStream(\ to = new FileOutputStream(\

15

byte[] buffer = new byte[4096]; int bytes_read;

while ( (bytes_read = from.read(buffer)) != -1) { to.write(buffer, 0, bytes_read); }

from.close(); to.close();

}catch (IOException e) { e.printStackTrace();

}

} }

一个完整的copy文件的参考程序如下: import java.io.*; class CopyFile{

public boolean copy(String fromFileName, String toFileName,boolean override) { File fromFile = new File(fromFileName); File toFile = new File(toFileName);

if (!fromFile.exists() || !fromFile.isFile() || !fromFile.canRead()) { return false; }

if (toFile.isDirectory()) {

toFile = new File(toFile, fromFile.getName()); }

if (toFile.exists()) {

if (!toFile.canWrite() || override == false) { return false; } }

else {

String parent = toFile.getParent(); if (parent == null) {

parent = System.getProperty(\ }

File dir = new File(parent);

if (!dir.exists() || dir.isFile() || !dir.canWrite()) { return false; } }

FileInputStream from = null; FileOutputStream to = null; try {

from = new FileInputStream(fromFile); to = new FileOutputStream(toFile); byte[] buffer = new byte[4096]; int bytes_read;

while ( (bytes_read = from.read(buffer)) != -1) { to.write(buffer, 0, bytes_read);

16

}

return true; }

catch (IOException e) { return false; }

finally {

if (from != null) { try {

from.close(); }

catch (IOException e) { } }

if (to != null) { try {

to.close(); }

catch (IOException e) { } } } }

public static void main(String args[]){ CopyFile cf=new CopyFile();

if(cf.copy(\ System.out.println(\文件拷贝成功!\ } else{

System.out.println(\文件未拷贝!\ } } }

3、编写一个程序,类名为WordCount,统计单词“hello”在一篇英文文章(保存在文件article.txt)中出现的次数,要求统计时忽略单词的大小写,统计结果在屏幕上打印出来的格式为:单词***在文章***中出现的次数为:10。 提示:下面是String类中的几个方法:

(1) public int indexOf(String str) //返回指定子字符串在此字符串中第一次出现处的

索引。

(2) public int indexOf(String str,int fromIndex) //从指定的索引开始,返回指定子字

符串在此字符串中第一次出现处的索引。

(3) public String toUpperCase() // String 中的所有字符都转换为大写 (4) public String toLowerCase () // String 中的所有字符都转换为小写 参考代码如下:

import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; class WordCount{

int getWordCount(String articleName,String word){ int count=0;

17

String sentence; try{

BufferedReader br=new BufferedReader(new FileReader(articleName)); word=word.toLowerCase();

while((sentence=br.readLine())!=null){ sentence=sentence.toLowerCase(); int index=sentence.indexOf(word); while(index>=0){ count++;

index=sentence.indexOf(word,index+word.length()); } }

}catch(IOException e){} return count; }

public static void main(String args[]){ String article=\ String word=\

WordCount w=new WordCount();

System.out.println(\单词\在文章\中出现的次数为:\ } }

4、编写一个程序N_Digital.java,随机生成n个数,n的值也随机生成,n的取值范围为10~50。要求将生成的n个数从大到小排序写入n.txt文件保存。 参考代码如下: import java.io.*;

public class N_Digital{

public void initNum(int[] num){ if (num == null) {

throw new NullPointerException(\参数不能为null!\ }

for (int i=0;i

num[i]=(int)(Math.random()*40)+10; System.out.print(num[i]+\ } }

public void sortNum(int[] obj){ if (obj == null) {

throw new NullPointerException(\参数不能为null!\ }

int tmp;

for (int i = 0 ;i < obj.length ;i++ ){

//切记,每次都要从第一个开始比。最后的不用再比。 for (int j = 0 ;j < obj.length -i -1 ;j++ ) { //对邻接的元素进行比较,如果后面的小,就交换 if (obj[j]

18

obj[j] = obj[j+1]; obj[j+1] = tmp; } //if } //for } //for }

public void writeToFile(int[]num,String file){ try{

File f=new File(file);

if(!f.exists())f.createNewFile();

PrintWriter out = new PrintWriter(new FileWriter(file)); for(int i=0;i

System.out.print(num[i]+\ }

out.close();

}catch(IOException ioe){ } }

public static void main(String []args){ int n=(int)(Math.random()*40)+10; int num[]=new int[n];

N_Digital nd=new N_Digital(); nd.initNum(num); nd.sortNum(num);

System.out.println();

nd.writeToFile(num,\ } }

5、编写一个Java程序ReadFileContent.java读取当前目录下的Test.txt文件内容(内容含有中文字),将该文件的内容按行读取出来,并在每行前面加上行号后写入当前目录的myTest.txt文件中。 import java.io.*;

class ReadFileContent{

public static void main(String args[]){ int i=0; try {

BufferedReader br = new BufferedReader(new FileReader(\ String line = br.readLine();

PrintWriter out = new PrintWriter(new FileWriter(\ while(line!=null){ i++;

out.println(i+\ line = br.readLine(); }

19

br.close(); out.close(); }catch (Exception e) { e.printStackTrace(); } } }

6、编写一个程序WriteLog.java实现如下功能:从键盘输入若行文字(可能包含中文),当最后一行输入quit#时,退出程序且将输入内容除quit#外全部存入文件c:\\log.txt中。 参考答案:

import java.io.*;

public class WriteLog {

public static void main(String []args){ String f=\ String str=\ try{

BufferedReader keyIn=new BufferedReader(new InputStreamReader(System.in));

PrintWriter bw=new PrintWriter(new FileWriter(f)); System.out.println(\ while(!(str=keyIn.readLine()).equals(\ bw.println(str); }

bw.close();

}catch(IOException e){ } } }

7、根据以下说明,编写一个银行账户类Account,并编写一个main方法,对Account类进行测试,在main方法中要调用Account的所有方法,发生异常时,要打印异常信息。 该类的成员变量如下(访问权限均为private): 变量名 含义 数据类型 Id 帐号 String Owner 账户持有人姓名 String Balance 余额 double 该类的成员方法如下(访问权限均为public): 方法名 参数 说明 构造方法 无 构造一个账户实例,将id,owner设为null,balance设为0.00 构造方法 String id, String owner, 构造一个账户实例,用参double amount 数设置成员变量id,ownerl,balance的值 setID String id 用参数设置成员变量id的值。返回类型void。 setOwner String owner 用参数设置成员变量owner的值。返回类型void。 Deposit double amount 将金额amount存入帐户,

20

Withdraw double amount Query 无 如果帐号为null,则抛出异常,异常信息为“帐号未知!”。返回类型double,返回值为amount。 从帐户支取金额amount,如果帐号为null,或者余额小于amount,则抛出异常,异常信息分别为“帐号未知!”和“余额不足!”。返回类型double,返回值为amount。 打印id,owner,balance。返回类型void。 参考答案: class Account {

private String id; private String owner; private double balance;

public Account() {

id=null; owner=null; balance=0.00; }

public Account(String id,String owner,double balance) {

this.id=id;

this.owner=owner; this.balance=balance; }

public void setID(String id) {

this.id=id; }

public void setowner(String owner) {

this.owner=owner; }

public double deposit(double amount) throws Exception {

if (id==null)

throw new Exception(\帐号未知!\ else {

balance+=amount; return amount; }

21

}

public double withdraw(double amount) throws Exception {

if (id==null)

throw new Exception(\帐号未知!\ else if (balance

throw new Exception(\余额不足!\ else {

balance-=amount; return amount; } }

public void query() {

System.out.println (\帐号:\户名:\余额:\ }

public static void main(String [] args) {

try{

Account ac1=new Account(\张三\ ac1.query();

ac1.deposit(2000); ac1.query();

ac1.withdraw(5000); ac1.query();

Account ac2=new Account(); ac2.query();

ac2.setID(\ ac2.setOwner(\李四\ ac2.deposit(2000); ac2.query();

ac2.withdraw(5000); ac2.query();

}catch(Exception e) {

System.out.println (e.getMessage()); } } }

8、编写类HandInput.java,该类接受用户的键盘输入,存入指定的文件。用户的输入以行为单位,当用户输入end时,程序结束。如果指定的文件已经存在,程序提示用户,并结束程序。 参考答案

import java.io.*; class HandInput {

public static void main(String [] args)

22

}

{ }

String inline;

BufferedReader handin=null; PrintWriter fostream=null; try {

File f=new File(args[0]); if (f.exists()) {

System.out.println (\目标文件已经存在。请换一个文件名!\ return; }

handin = new BufferedReader(

new InputStreamReader(System.in)); fostream = new PrintWriter(new FileWriter(f)); while (true) {

inline=handin.readLine(); if (!inline.equals(\ {

fostream.println(inline); } else {

break; } } }

catch(IOException e) {

System.out.println (\操作失败!\ }

finally {

try {

if (handin!=null) handin.close(); if (fostream!=null) fostream.close(); }

catch(Exception e1){} }

23