附录 实训参考答案
} finally { System.out.println(\ } } }
说明:捕获异常的顺序和不同catch语句的顺序有关,当捕获到一个异常时,剩下的catch语句就不再进行匹配。因此,在安排catch语句的顺序时,首先应该捕获最特殊的异常,然后再逐渐一般化。也就是一般先安排子类,再安排父类。 3. public class ExceptionExam4 {
public static void main(String [] args) { try { int [] a=new int[3];
a[2]=4;
return; } catch(ArithmeticException e) { System.out.println(\发生了异常\ //或者return;
// System.exit(0);
} finally { System.out.println(\ } }
}
说明:不论在try代码块中是否发生了异常事件,finally块中的语句都会被执行。无论捕获异常都要执行;在try块或catch块中有return语句。Finally块不执行的条件:在try块或catch块中执行了System.exit()方法,终止虚拟机。
4.
import java.io.*;
public class ExceptionExam5
279
Java语言程序设计基础 { public static void go() throws IOException { }
public static void main(String [] args) { try { go(); } catch(IOException e){ } catch(RuntimeException e){ } catch(Exception e){ } catch(Error e){} catch(Throwable e){ } }
}
说明:Catch块的次序从小到大。层次相同的没有次序要求。 5. public class ExceptionExam6 extends Exception
{ public ExceptionExam15(String msg) { super(msg); } public static void main(String [] args) throws Exception { throw new ExceptionExam6(\用户自行产生异常\
}
}
说明: 声明抛弃异常是在一个方法声明中的throws子句中指明的;throws子句中同时可以指明多个异常,说明该方法将不对这些异常进行处理,而是声明抛弃它们。
实训14 文件属性的访问
实训内容
编写一个程序,使它能够像DOS操作系统命令Dir的功能,列出指定目录内所有文件和目录的相关信息。
280
附录 实训参考答案 参考答案
import java.io.*; import java.util.Date; public class Jdir{ public static void main(String args[]){ String dir; int x=0,y=0; long sum=0; try{ dir=args[0]; }catch(ArrayIndexOutOfBoundsException e){ dir=\ } File f=new File(dir); if(!f.exists()){ System.out.println(\文件或目录不存在!\
System.exit(0); }
else if(f.isDirectory()){ File ls[]=f.listFiles(); Date fd; for(int i=0;i 281 Java语言程序设计基础 } } System.out.print(f.length()+\ System.out.println(f.getName()); y++; sum=f.length(); } System.out.println(\个文件\\t\\t\\t\字节\System.out.println(\个目录\\t\ 实训15 文本文件的读写 实训内容 编写一个程序,能够完成对一个文本文件的复制功能。源文件名和目标文件名都在命令行中指定,同时在屏幕上输出该文件的内容。 参考答案 import java.io.*; class CopyFile { public static void main(String[] args) { String file1=\ int ch; long cnt=0; if(args.length==2) { if(args[0].equals(args[1])){ System.out.println(\源文件名和目标文件名不能相同!\ System.exit(0);} else{ file1=args[0]; file2=args[1]; } }else { System.out.println(\请指定源文件名和目标文件名!\ System.exit(0); } try{ FileInputStream fis = new FileInputStream(file1); 282 附录 实训参考答案 FileOutputStream fos=new FileOutputStream(file2); cnt=fis.available(); while ((ch=fis.read())!=-1){ System.out.write(ch); fos.write(ch); } fis.close(); fos.close(); } catch(FileNotFoundException e){ System.out.println(\源文件:未找到!\ } } System.exit(-1); } catch (IOException e){ System.out.println(e.toString()); } System.out.println(\复制文件完成,共\个字节!\ 实训16 随机文件的读写 实训内容 编写一个程序,结合教材本章例子8-6所创建的student.dat文件,能够实现对学生记录的随机访问,要求输入记录号,读出该记录对应的学生信息。 参考答案 import java.io.*; class AccessFile { public static void main(String[] args) { int n; byte b[]; System.out.print(\请输入记录号:\ try{ RandomAccessFile ra=new RandomAccessFile(\ b=new byte[4]; System.in.read(b); String str=new String(b); 283