程序员玩转算法韩顺平-清华教程lesson_第1页
程序员玩转算法韩顺平-清华教程lesson_第2页
程序员玩转算法韩顺平-清华教程lesson_第3页
程序员玩转算法韩顺平-清华教程lesson_第4页
程序员玩转算法韩顺平-清华教程lesson_第5页
已阅读5页,还剩49页未读 继续免费阅读

付费下载

下载本文档

版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领

文档简介

1、课前思考例外?Java中有哪两种例外处理机制?字节流和字符流的基类各是什么?对象的串行化?对象串行化的作用是什么?2第四讲 Java的例外处理和输入输出流1难点和重点如何使用Java中两种例外处理机制的方法,抛弃例外和 抛弃例外的区别与联系。对象串行化的概念。遇到实际问题时,要根据需要正确使用各种输入出流,特别是对中文使用适当的字符输入流。4学习目标本讲主要讲述java语言中的输入/出的处理和独特的例外处理机制,通过本讲的学习,可以编写更为完善的java程序。3例外例外就是在程序的运行过程中所发生的异常事件,它中断指令的正常执行。6第九章 例外处理5例外示例C:javac ExceptionD

2、emol.javaExceptionDemo1.java:6: Exception java.io.FileNotFoundException must be caught, or it must be declaredhe throws clause of this method.FileInputStream fis = new FileInputStream( text );ExceptionDemo1.java:8: Exception java.io.IOException must be caught, or it must be declaredhe throws clause

3、of this method.while( (b=fis.read()!=-1 )2 errors8例外示例import java.io.*;class ExceptionDemo1public sic void main( String args ) FileInputStream fis = new FileInputStream( text );b;while( (b=fis.read()!=-1 ) System.out.pr( b );fis.close( );7例外示例C:javac ExceptionDemo2.javaC:java ExceptionDemo2java.lang

4、.ArithmeticException: / by zeroatExceptionDemo2.main(ExceptionDemo2.java:4)10例外示例class ExceptionDemo2public sic void main( String args ) a = 0;System.out.prln( 5/a );9例外处理机制当Java运行时系统得到一个例外对象时, 它将会寻找处理这一例外的代码。找到 能够处理这种类型的例外的方法后,运 行时系统把当前例外对象交给这个方法 进行处理,这一过程称为捕获(catch)例外。如果Java运行时系统找不到可以捕获例外的方法,则运行时系

5、统将终止,相应的 Java程序也将退出。12例外处理机制在Java程序的执行过程中,如果出现了异常事件,就会生成一个例外对象。生成的例外对象将传递给Java运行时系统,这一例外的产生和提交过程称为抛弃(throw)例外。11LinkageErrorErrorVirtualMachineErrorAWTErrorArithmeticException.ThrowableIndexOutOfBounds.RuntimeExceptionerruptedException.ExceptionIOExceptionFileNotFoundExceptionEOFException.AWTExcepti

6、on.14例外(Throwable)分类Error动态 失败,虚拟机错误等,通常Java程序不应该捕获这类例外,也不会抛弃这种例外。Exception运行时例外继承于RuntimeException。Java编译器允许程序不对它们做出处理。非运行时例外除了运行时例外之外的其他由Exception继承来的例外类。Java编译器要求程序必须捕获或者 抛弃这种例外。13try捕获例外的第一步是用try选定捕获例 外的范围,由try所限定的代码块中的语句 在执行过程中可能会生成例外对象并抛弃。16捕获例外捕获例外是通过try-catch-finally语句实现的。try.catch( Exceptio

7、nName1 e ).catch( ExceptionName2 e ).finally.15try.catch( FileNotFoundException e ) System.out.prln( e );System.out.prln(message: +e.getMessage() );e.prStackTrace( System.out );catch( IOException e ) System.out.prln( e );18catch每个try代码块可以伴随一个或多个catch语句,用于处理try代码块中所生成的例外事件。catch语句只需要一个形式参数指明它所能够捕获的例外

8、类型,这个类必须是Throwable的子类,运行时系统通过参数值把被抛弃的例外对象传递给catch块.在catch块中是对例外对象进行处理的代码,与其它对象一样,可以一个例外对象的变量或调用它的方法。getMessage( )是类Throwable所提供的方法,用来得到有关异常事件的信息,类Throwable还提供了方法prStackTrace( )用来异常事件发生时执行堆栈的内容。17finally捕获例外的最后一步是通过finally语句为例外处理提供一个的出口,使得在控制流转到程序的其它部分以前,能够对程序的状态作的管理。不论在try代码块中是否发生了异常事件,finally块中的语句都

9、会被执行。20catch语句的顺序捕获例外的顺序和不同catch语句的顺序有关,当捕获到一个例外时,剩下的catch语句就不再进行匹配。因此,在安排catch语句的顺序时,首先应该捕获最特殊的例外,然后再逐渐一般化。也就是一般先安排子类,再安排父类。19抛弃例外如果在一个方法中生成了一个例外,但是这一方法并不确切地知道该如何对这一异常事件进行处理,这时,一个方法就应该 抛弃例外,使得例外对象可以从调用栈向后 ,直到有合适的方法捕获它为止。22tryb=0; System.out.prln(5/b);catch(ArithmeticException e) finallyif (fis!=nul

10、l) System.out.prln(“closingFileInputStream”);elseSystem.out.prln(“FileInputStream not open”);21抛弃例外抛弃例外首先要生成例外对象,例外或者由虚拟机生成,或者由某些类的实例生成,也可以在程序中生成。生成例外对象是通过throw语句实现的。IOException e=new IOException(); throw e ;可以抛弃的例外必须是Throwable或其子类的实例。下面的语句在编译时将会产生语法错误:throw new String(want to throw);24抛弃例外抛弃例外是在一个方

11、法中的throws子句中指明的。例如:publicread () throws IOException.throws子句中同时可以指明多个例外,说明该方法将不对这些例 行处理,而是 抛弃它们:publicsicvoidmain(Stringargs)throws IOException,IndexOutOfBoundsException 23例外类的使用FileInputStream 的APIpublic FileInputStream(String name) throws FileNotFoundException26例外类的使用自定义例外类必须是Throwable的直接或间接子类一个方法

12、所 抛弃的例外是作为这个方法与外界交互的一部分而存在的。方法的调用者必须了解这些例外,并确定如何正确的处理他们。25例外类的使用积极处理方式:import java.io.*;class ExceptionDemo1public sic void main( String args ) try FileInputStream fis = newFileInputStream( text ); catch(FileNotFoundException e) 28例外示例import java.io.*;class ExceptionDemo1public sic void main( String

13、 args ) FileInputStreamfis=newFileInputStream( text );27例外类的使用如果采用消极处理方式,则由调用该方法的方法进行处理;但是调用该方法的方法也可以采用消极和积极两种处理方式,一直传递到Java运行环境.30例外类的使用消极处理方式:import java.io.*;class ExceptionDemo1public sic void main( String args ) throws FileNotFoundExceptionFileInputStream fis = newFileInputStream( text );29例外类的

14、使用(3)在自定义例外类时,如果它所对应的异常事件通常总是在运行时产生的,而且不容易 它将在何时、何处发生,则可以把它定义为运行时例外,否则应定义为非运行时例外。32例外类的使用运行时例外则表示由运行时系统所检测到的程序设计问题或者API的使用不当问题,它可能在程序的任何地方出现:对于运行时例外,如果不能它何时发生,程序可以不做处理,而是让Java虚拟机去处理它。如果程序可以预知运行时例外可能发生的地点和时间,则应该在程序中进行处理,而不应简单的把它交给运行时系统。31java.io包字节流从InputStream和OutputStream派生出来的一系列类。这类流以字节(byte)为基本处理

15、 。字符流从Reader和Writer派生出的一系列类,这类流以16位的Unicode码表示的字符为基本处理单位。34第十章 输入/输出处理33字符流Reader、WriterInputStreamReader、OutputStreamWriterFileReader、FileWriterCharArrayReader、CharArrayWriterPipedReadipedWriterFilterReader、FilterWriterBufferedReader、BufferedWriterStringReader、StringWriter36字节流InputStream、OutputStr

16、eamFileInputStream、FileOutputStreamPipedInputStreipedOutputStreamByteArrayInputStream、ByteArrayOutputStreamFilterInputStream、FilterOutputStreamDataInputStream、DataOutputStreamBufferedInputStream、BufferedOutputStream35其它文件处理File、RandomAcsFile;接口DataInput、DataOutput、ObjectInput、 ObjectOutput;38对象流Obje

17、ctInputStream、ObjectOutputStream37I/O处理的类层次ObjectOutputStream FileOutputStreamOutputStreamPipedOutputStreamByteArrayOutputStreamDataOutputStreamFilterOutputStreamBufferedOutputStream Pr Stream40FileNameFilterStreamTokenizerFileDescriptorFileDataOutputRandomAcsFileObjectOutputI/O处理的类层次FileInputStream

18、 PipedInputStreamByteArrayInputStreamBufferedInputStream InputStreamSequenceInputStreamLineNumberInputStreamStringBufferInputStreamPushbackInputStreamFilterInputStreamDataInputStream ObjectInputStreamRandomAcsF39ileObjectInputDataInputInputStream关闭流close( );使用输入流中的标记 void mark( readlimit ); void res

19、et( );markSupported( );42InputStream从流中数据read( );read( byte b );read( byte b ,off,len ); available( );long skip( long n );41文件处理File、FileInputStream、FileOutputStream、 RamdomAcsFile44OutputStream输出数据void write(b ); void write( byte b );void write( byte b ,off,len );flush( )刷空输出流,并输出所有被缓存的字节。关闭流close(

20、 );43文件描述文件名的处理String getName( );/*得到一个文件的名称(不包括路径)*/String getPath( );/得到一个文件的路径名 String getAbsolutePath( );/*得到一个文件的绝对路径名*/String getParent( );/*得到一个文件的上一级目录名*/String renameTo(File newName);/*将当前文件名更名为给定文件的完整路径*/46文件描述类File提供了一种与机器无关的方式来描述一个文件对象的属性。文件的生成public File(String path);public File(String

21、path,String name); public File(File dir,String name);45文件描述普通文件信息和工具long lastModified( );/*得到文件最近一次修改的时间*/long length( );/得到文件的长度,以字节为 delete( );/删除当前文件目录操作mkdir( );/*根据当前对象生成一个由该对象指定的路径*/ String list( );/列出当前目录下的文件48文件描述文件属性测试exists( );/*测试当前File对象所指示的文件是否存在*/canWrite( );/测试当前文件是否可写 canRead( );/测试当

22、前文件是否可读 isFile( );/*测试当前文件是否是文件(不是目录)*/ isDirectory( );/*测试当前文件是否是目录*/47System.out.pr ln(name+f.getName(); System.out.prln(path+f.getPath();System.out.prln(absolute path+f.getAbsolutePath(); System.out.pr ln(parent+f.getParent(); System.out.prln(is a file?+f.isFile();System.out.pr ln(is a directory?

23、+f.isDirectory(); System.out.pr ln(length+f.length(); System.out.pr ln(can read+f.canRead(); System.out.pr ln(can write+f.canWrite(); System.out.prln(last modified+f.lastModified(); File newF=new File(newFile);System.out.prln(. Rename +f+.); f.renameT F);50例10.1import java.io.*; class FileTestpublic

24、 sic void main(String args)System.out.prln(path separator+File.pathSeparator);System.out.prln(path separator char+File.pathSeparatorChar);System.out.prln(separator+File.separator); system.out.prln(separator char+File.separatorChar); File f=new File(/dong1/test1.class);System.out.prln(); System.out.p

25、rln(f);System.out.prln(exist?+f.exists();49运行结果path separator:path separator char:separator / separator char /dong1/test1.class exist? truename test1.classpath /dong1/test1.classabsolute path /dong1/test1.classparent /dong152System.out.prln(name +newF.getName(); System.out.pr ln(f+exist?+f.exists();

26、 System.out.prln(. delete+newF+.); newF.delete();System.out.prln(newF+exist?+newF.exists();51文件处理列出目录中与某种模式相匹配的文件:public String list(FilenameFilter filter);在接口FilenameFilter中定义的方法只有: accept(File dir,String name);54运行结果is a file? trueis a directory? false length 514can readtrue can write truelast mod

27、ified 907117020000. Rename /dong1/test1.class name newFile/dong1/test1.class exist? false. delete newFile .newFile exist? false53for (i=0;ifiles.length;i+) File f=new File(filesi);if(f.isFile()System.out.prln(“file”+f); elseSystem.out.prln(“sub directory”+f);56例10.2import java.io.*;public class File

28、FilterTestpublic sic void main(String args) File dir=new File(“/dongl”); Filter filter=new Filter(“htm”);System.out.prln(“list html files in directory ”+dir);String files=dir.list(filter);55运行结果list html files in directoty /dongl file cert_test.htmfile cert_sle.htm file cert_obj.htm58class Fileter i

29、mplements FilenameFilter String extent;File(String extent) this.extent=extent;publicaccept(File dir,String name)return name.endsWith(“.”+extent);57FileInputStream fis; tryfis = new FileInputStream( text ); System.out.pr( content of text is : );b;while( (b=fis.read()!=-1 ) System.out.pr( (char)b );ca

30、tch( FileNotFoundException e ) System.out.prln( e );catch( IOException e ) System.out.prln( e );60文件的顺序处理类FileInputStream和FileOutputStream用来进行文件I/O处理,由它们所提供的方法可以打开本机上的文件,并进行顺序的读/写。59随机存取文件构造方法:RandomAcsFile(String name,String mode); RandomAcsFile(File file,String mode);文件指针的操作 long getFilePoer( ); v

31、oid seek( long);skipBytes(n );62随机存取文件public class RandomAcsFile extends Objectimplements DataInput, DataOutput接口DataInput中定义的方法主要包括从流中基本类型的数据、 一行数据、或者 指定长度的字节数。如:read( )、read ( )、 readLine( )、readFully( )等。接口DataOutput中定义的方法主要是向流中写入 基本类型的数据、或者写入一定长度的字节数组。如:writeChar( )、writeDouble( )、write( )等。61过滤

32、流过滤流在读/写数据的同时可以对数据进行处理,它提供了同步机制,使得某一时刻只有一个线程可以 一个I/O流,以防止多个线程同时对一个I/O流进行操作所带来的意想不到的结果。类FilterInputStream和FilterOutputStream分别作为所有过滤输入流和输出流的父类。64随机存取文件例10.4(见书上106页)63过滤流BufferedInputStream和BufferedOutputStream缓冲流,用于提高输入/输出处理的效率。java.lang.Object|+java.io.InputStream|+java.io.FilterInputStream|+java.i

33、o.BufferedInputStream66过滤流为了使用一个过滤流,必须首先把过滤流连接到某个输入/出流上,通常通过在构造方法的参数中指定所要连接的输入/出流来实现。例如:FilterInputStream( InputStream in ); FilterOutputStream( OutputStream out );65过滤流DataInputStreambytereadByte()long readLong() doublereadDouble()DataOutputStreamvoidwriteByte(byte) void wriong(long)voidwriteDouble

34、(double)68过滤流DataInputStream 和DataOutputStream可以以与机器无关的格式各种类型的数据。public class DataInputStream extends FilterInputStream implements DataInput67例10.5import java.io.*;public class getIdentifierpublic sic void main(String args) tryFileInputStream fis=new FileInputStream(“test”);PushbackInputStreis=new P

35、ushbackInputStream(fis);data;in idNum=0;70过滤流LineNumberInputStream除了提供对输入处理的支持外,LineNumberInputStream可以当前的行号。PushbackInputStream提供了一个方法可以把刚读过的字节退回到输入流中。PrStream打印流的作用是把Java语言的内构类型以其字符表示形式送到相应的输出流。69dodata=pis.read();while(data!=- 1)&!Character.isLetter(char)data);pis.unread(data);System.out.prln(“fi

36、nd”+idNum+ “ identifiers”);catch(FileNotFoundException e) System.out.prln(“error”+e);72dodata=pis.read();while(data!=- 1)&!Character.isLetter(char)data);pis.unread(data); while(data=pis.read()!=-1)if(Character.isLetterOrDigit(char)data) System.out.pr(char)data);elseidNum+; System.out.prln();71运行结果ja

37、va is not only aprogramming languagefind 7 identifiers74catch(IOException e) System.out.prln(“error”+e);文件“test”的内容为:1java is not %only2#a programming language73流结束的判断read()返回-1。read()read()、readByte()、readLong()、 readDouble()等;产生EOFException。readLine( )返回null。76I/O例外进行I/O操作时可能会产生I/O例外,属于非运行时例外,应该在程

38、序中处理。如:FileNotFoundException, EOFException, IOException75ReaderReader类是处理所有字符流输入类的父类。字符publicread() throws IOException;publicread(char cbuf) throws IOException; public abstractread(char cbuf,off,len)throws IOException;78字符流java.io包中提供了专门用于字符流处理的类(以Reader和Writer为基础派生出的一系列类)。Reader和Writer这两个类是抽象类,只是提供

39、了一系列用于字符流处理的接口,不能生成这两个类的实例,只能通过使用由它们派生出来的子类对象来处理字符流。77WriterWriter类是处理所有字符流输出类的父类。 向输出流写入字符public void write(c) throws IOException; public void write(char cbuf) throws IOException; public abstract void write(char cbuf,off,len)throws IOException;public void write(String str) throws IOException; publi

40、c void write(String str,off,len) throwsIOException;80Reader标记流publicmarkSupported();public void mark(readAheadLimit) throws IOException;public void reset() throws IOException;关闭流public abstract void close() throws IOException;79InputStreamReader和OutputStreamWriterjava.io包中用于处理字符流的最基本的类,用来在字节流和字符流之间作

41、为中介。82Writerflush( )刷空输出流,并输出所有被缓存的字节。关闭流public abstract void close() throws IOException;81InputStreamReader和OutputStreamWriter读入和写出字符基本同Reader和Writer。获取当前编码方式public String getEncoding();关闭流public void close() throws IOException;84InputStreamReader和OutputStreamWriter生成流对象public InputStreamReader(Inp

42、utStream in);public InputStreamReader(InputStream in,String enc) throws UnsupportedEncodingException;public OutputStreamWriter(OutputStream out); public OutputStreamWriter(OutputStream out,Stringenc) throws UnsupportedEncodingException;83BufferedReader和BufferedWriter读入/写出字符除了Reader和Writer中提供的基本的读写方法

43、外,增加对整行字符的处理。 public String readLine() throws IOException;public void newLine() throws IOException;86BufferedReader和BufferedWriter生成流对象public BufferedReader(Reader in); public BufferedReader(Reader in,sz); public BufferedWriter(Writer out); public BufferedWriter(Writer out, sz);85运行结果如下:Read: java i

44、s a platform independent Read: programming languageRead: it is aRead: object oriented language.88import java.io.*;public class CharInputpublic sic void main(String args) throws FileNotFoundException,IOExceptionString s; FileInputStream is; InputStreamReader ir; BufferedReader in;is=new FileInputStre

45、am(“test.txt”); ir=new InputStreamReader(is); in=new BufferedReader(ir); while(s=in.readLine()!=null) System.out.prln(Read: +s); 87注意:在 字符流时,如果不是来自于本地的,比如说来自于网络上某处的与本地编码方式不同的机器,那么 在构造输入流时就不能简单地使用本地缺省的编码方式,否则读出的字符就不正确;为了正确地读出异种机上的字符, 应该使用下述方式构造输入流对象:ir = new InputStreamReader(is, “8859_1”);采用ISO 8859

46、_1编码方式,这是一种到ASCII码的编码方式,可以在不同之间正确转换字符。90从键盘接收输入的数据InputStreamReader ir; BufferedReader in;ir=new InputStreamReader(System.in); in=new BufferedReader(ir);String s=in.readLine();System.out.prln(“Input value is: ”+s); i =egarse(s);/转换成 型i*=2;System.out.prln(“Inputvaluechangedafter doubled: ”+i);89串行化方法

47、在java.io包中,接口Serializable用来作为实现对象串行化的工具,只有实现了 Serializable的类的对象才可以被串行化。92对象的串行化(Serialization)对象自己的状态以便将来再生的能力,叫作对象的持续性(persistence)。对象通过写出描述自己状态的数值来自己,这个过程叫对象的串行化 (Serialization)。91构造对象的输入输出流java.io包中,提供了ObjectInputStream和 ObjectOutputStream将数据流功能扩展至可读写对象。在ObjectInputStream中用 readObject()方法可以直接一个对象

48、, ObjectOutputStream中用writeObject()方法可以直接将对象保存到输出流中。94定义一个可串行化对象public class Student implements Serializableid;/学号String name;/ age;/String department /系别public Student(id,String name,age,String department)this.id = id; = name; this.age = age;this.department = department;93恢复对象状态FileInputStream fi=new FileInputStream(data.ser); ObjectInputStream si=new ObjectInputStream(fi); trystu=(Student)si

温馨提示

  • 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
  • 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
  • 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
  • 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
  • 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
  • 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
  • 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。

最新文档

评论

0/150

提交评论