第九章输入输出处理

上传人:夏** 文档编号:568487680 上传时间:2024-07-24 格式:PPT 页数:61 大小:153.01KB
返回 下载 相关 举报
第九章输入输出处理_第1页
第1页 / 共61页
第九章输入输出处理_第2页
第2页 / 共61页
第九章输入输出处理_第3页
第3页 / 共61页
第九章输入输出处理_第4页
第4页 / 共61页
第九章输入输出处理_第5页
第5页 / 共61页
点击查看更多>>
资源描述

《第九章输入输出处理》由会员分享,可在线阅读,更多相关《第九章输入输出处理(61页珍藏版)》请在金锄头文库上搜索。

1、第九章 输入/输出处理合肥学院计算机系本讲内容1、I/O概述2、I/O字节流3、I/O字符流4、随机访问文件21. I/O概述 大部分程序都需要输入/输出处理,比如从键盘读取数据、向屏幕中输出数据、从文件中读或者向文件中写数据、在一个网络连接上进行读写操作等。在Java中,把这些不同类型的输入、输出抽象为流(Stream),而其中输入或输出的数据则称为数据流(Data Stream),用统一的接口来表示,从而使程序设计简单明了。31. I/O概述流一般分为输入流(Input Stream)和输出流(Output Stream)两类,但这种划分并不是绝对的。比如一个文件,当向其中写数据时,它就是

2、一个输出流;当从其中读取数据时,它就是一个输入流。当然,键盘只是一个数人流,而屏幕则只是一个输出流。在Java开发环境中,主要是由包java.io中提供的一系列的类和接口来实现输入/输出处理。标准输入/输出处理则是由包java.lang中提供的类来处理的,但这些类又都是从包java.io中的类继承而来。41. I/O概述在JDK1.1之前,java.io包中的流只有普通的字节流(以byte为基本处理单位的流),这种流对于以16位的Unicode码表示的字符流处理很不方便。从JDK1.1开始, java.io包中加入了专门用于字符流处理的类(以Reader和Writer为基础派生的一系列类)。另

3、外,为了使对象的状态能够方便地永久保存下来, JDK1.1以后的java.io包中提供了以字节流为基础的用于对象的永久化保存状态的机制(通过实现ObjectInput和ObjectOutput接口)。51. I/O字节流InputStream nByteArrayInputStream nFileInputStream nFilterInputStream wBufferedInputStream wDataInputStreamwLineNumberInputStream wPushbackInputStreamnObjectInputStreamnPipedInputStream nSeq

4、uenceInputStream nStringBufferInputStreamOutputStreamnByteArrayOutputStreamnFileOutputStreamnFilterOutputStreamwBufferedOutputStreamwDataOutputStreamwPrintStreamnObjectOutputStreamnPipedOutputStream61. I/O字符流ReadernBufferedReaderwLineNumberReadernCharArrayReadernFilterReaderwPushbackReadernInputStre

5、amReaderwFileReadernPipedReadernStringReaderWriternBufferedWriternCharArrayWriternFilterWriternOutputStreamWriterwFileWriternPipedWriternStringWriternPrintWriter71. I/O接口 与 文件操作DataInputnObjectInputDataOutputnObjectOutputFileFilterFilenameFilterObjectInputValidationObjectStreamConstantsSerializablen

6、ExternalizableFileFileDescriptorRandomAccessFile java.awt.FileDialog82. 字节流InputStream read():从流中读入数据skip():跳过流中若干字节数available():返回流中可用字节数mark():在流中标记一个位置reset():返回标记过得位置markSupport():是否支持标记和复位操作close():关闭流92. 字节流InputStreamint read() n从输入流中读一个字节,形成一个0255之间的整数返回(是一个抽象方法)。int read(byte b) n读多个字节到数组中。

7、int read(byte b, int off, int len)n从输入流中读取长度为len的数据,写入数组b中从索引off开始的位置,并返回读取得字节数。对于这三个方法,若返回1,表明流结束。102. 字节流OutputStreamwrite(int b) n将一个整数输出到流中(只输出低位字节,抽象)write(byte b) n将字节数组中的数据输出到流中write(byte b, int off, int len) n将数组b中从off指定的位置开始,长度为len的数据输出到流中flush():刷空输出流,并将缓冲区中的数据强制送出close():关闭流112. 字节流例子1把输入

8、流中的所有内容复制到输出流中public void copy(InputStream in, OutputStream out) throws IOException byte buf = new byte4096; int len = in.read(buf); while (len != -1) out.write(buf, 0, len); len = in.read(buf); 122. 字节流文件流FileInputStream:类用来打开一个输入文件,若要打开的文件不存在,则会产生例外FileNotFoundException,这是一个非运行时例外,必须捕获或声明抛弃;FileOu

9、tputStream:类用来打开一个输出文件,若要打开的文件不存在,则会创建一个新的文件,否则原文件的内容会被新写入的内容所覆盖。在进行文件的读/写操作时,会产生非运行时例外IOException,必须捕获或声明抛弃(其它的输入/输出流处理时也同样需要进行输入/输出例外处理)。132. 字节流文件流文件流的构造方法:nFileInputStream(String name) w打开一个文件路径名为name的文件作为输入。nFileOutputStream(String name) w创建一个文件路径名为name的文件作为输出,文件如果已经存在,则其内容被清空。nFileOutputStream

10、(String name, boolean append) w创建一个文件路径名为name的文件作为输出,文件如果已经存在,则在该输出上输出的内容被接到原有内容之后。142. 字节流例子2把一个文件的内容加到另一个文件后public void cat(String fsrc, String fdest) try InputStream in = new FileInputStream(fsrc); OutputStream out = new FileOutputStream(fdest, true); copy(in, out); out.close(); in.close(); catch

11、 (IOException ex) System.err.println(ex); 152. 字节流过滤流类FilterInputStream和FilterOutputStream分别对其他输入/输出流进行特殊处理,它们在读/写数据的同时可以对数据进行特殊处理。另外还提供了同步机制,使得某一时刻只有一个线程可以访问一个输入/输出流。类FilterInputStream和FilterOutputStream分别重写了父类InputStream和OutputStream的所有方法,同时,它们的子类也应该重写它们的方法以满足特定的需要。要使用过滤流,首先必须把它连接到某个输入/输出流上,通常在构造方

12、法的参数中指定所要连接的流:nFilterInputStream(InputStream in);nFilterOutputStream(OutputStream out);这两个类是抽象类,构造方法也是保护方法。162. 字节流过滤流:缓冲流类BufferedInputStream和BufferedOutputStream实现了带缓冲的过滤流,它提供了缓冲机制,把任意的I/O流“捆绑”到缓冲流上,可以提高读写效率。在初始化时,除了要指定所连接的I/O流之外,还可以指定缓冲区的大小。缺省大小的缓冲区适合于通常的情形;最优的缓冲区大小常依赖于主机操作系统、可使用的内存空间以及机器的配置等;一般缓

13、冲区的大小为内存页或磁盘块等地整数倍,如8912字节或更小。nBufferedInputStream(InputStream in, int size) nBufferedOutputStream(OutputStream out, int size) 172. 字节流例子3使用缓冲流支持的mark和reset机制public String readLine( BufferedInputStream in) throws IOException StringBuffer sb = new StringBuffer(); int c = in.read(); return sb.toString

14、();while (c != -1) if (c = n) break; if (c = r) in.mark(1); if (in.read() != n) in.reset(); break; sb.append(char)c); c = in.read();182. 字节流过滤流:缓冲流对于BufferedOutputStream,只有缓冲区满时,才会将数据真正送到输出流,但可以使用flush()方法人为地将尚未填满的缓冲区中的数据送出。public void copy(InputStream in, OutputStream out) throws IOException out =

15、new BufferedOutputStream(out, 4096); byte buf = new byte4096; int len = in.read(buf); while (len != -1) out.write(buf, 0, len); len = in.read(buf); out.flush();192. 字节流DataInputboolean readBoolean() byte readByte() short readShort() char readChar() int readInt() long readLong() double readDouble() f

16、loat readFloat() int readUnsignedByte() int readUnsignedShort()202. 字节流DataInputvoid readFully(byte b) n读满字节数组,不同于InputStream.readvoid readFully(byte b, int off, int len) n读满指定长度,不同于InputStream.readint skipBytes(int n) n与InputStream.skip等价String readUTF() n安类UTF-8形式从输入中读取字符串String readLine()n按回车(r)换

17、行(n)为分割符读取一行字符串n不完全支持UNICODE212. 字节流DataOutputvoid writeBoolean(boolean v) void writeByte(int v) void writeShort(int v) void writeChar(int v)void writeInt(int v) void writeLong(long v) void writeFloat(float v) void writeDouble(double v) 222. 字节流DataOutputvoid write(byte b) n与OutputStream.write同义void

18、 write(byte b, int off, int len) n与OutputStream.write同义void write(int b) n与OutputStream.write同义void writeBytes(String s) n只输出每个字符的低8位;不完全支持UNICODE。void writeChars(String s) n每个字符在输出中都占两个字节。232. 字节流过滤流:数据流DataInputStream和DataOutputStreamn在提供了字节流的读写手段的同时,n以统一的通用的形式向输入流中写入boolean,int,long,double等基本数据类型

19、,并可以在次把基本数据类型的值读取回来。n提供了字符串读写的手段。n分别实现了DataInput和DataOutput接口242. 字节流例子4FileOutputStream fos = new FileOutputStream(“a.txt”);DataOutputStream dos = new DataOutputStream (fos);dos.writeBoolean(true);dos.writeByte(byte)123);dos.writeChar(J);dos.writeDouble(3.141592654);dos.writeFloat(2.7182f);dos.writ

20、eInt(1234567890);dos.writeLong(998877665544332211L);dos.writeShort(short)11223);dos.writeUTF(“字符串”);dos.close();252. 字节流例子4(续)FileInputStream fis = new FileInputStream(a.txt)DataInputStream dis = new DataInputStream(fis);System.out.println(dis.readBoolean();System.out.println(dis.readByte();System.o

21、ut.println(dis.readChar();System.out.println(dis.readDouble();System.out.println(dis.readFloat();System.out.println(dis.readInt();System.out.println(dis.readLong();System.out.println(dis.readShort();System.out.println(dis.readUTF();dis.close();262. 字节流过滤流:其它LineNumberInputStream:主要用于对文本文件的处理,提供了行号控制

22、功能。n已经被LineNumberReader取代PushBackInputStream:它提供了一个方法将刚刚读入的一个或多个字节退回到输入流中去。n在编译程序的词法分析阶段,经常要超前读入一个字节以界定当前词的属性,然后再将该字节退回(因为下面的处理可能还会用到该字节)。 PrintStream:其作用是将Java语言中的不同类型的数据以字符表示形式输出到相应的输出流中去。n不产生异常。可自动flush。通过checkError()检查错误。272. 字节流标准流语言包java.lang中的System类管理标准输入/输出流和错误流。System.in,从InputStream中继承而来,

23、用于从标准输入设备中获取输入数据(通常是键盘)。System.out,从PrintStream中继承而来,把输出送到缺省的显示设备(通常是显示器)。System.err,也是从PrintStream中继承而来,把错误信息送到缺省的显示设备(通常是显示器)。每当main方法被执行时,就自动生成上述三个对象。282. 字节流例子5public static void main(String args) try byte bArray=new byte128; String str; System.out.println(“Please enter something:); System.in.re

24、ad(bArray); str = new String(bArray); System.out.print(You entered:); System.out.println(str); catch(IOException ioe) System.err.println(ioe.toString(); 292. 字节流对象流对象的持续性(Persistence)n能够纪录自己的状态一边将来再生的能力,叫对象的持续性。对象的串行化(Serialization)n对象通过写出描述自己状态的的数值来记录自己的过程叫串行化。串行化的主要任务是写出对象实例变量的数值,如果变量是另一个对象的引用,则引用

25、的对象也要串行化。这个过程是递归的。对象流n能够输入输出对象的流称为对象流。n可以将对象串行化后通过对象输入输出流写入文件或传送到其它地方。302. 字节流对象流在java中,允许可串行化的对象在通过对象流进行传输。只有实现Serializable接口的类才能被串行化, Serializable接口中没有任何方法,当一个类声明实现Serializable接口时,只是表明该类加入对象串行化协议。public class Student implements Serializable int id; String name; int age; String department; transien

26、t int number; / 第几个对象实例 static int count; / 创建对象实例的计数器312. 字节流对象流 要串行化一个对象,必须与一定的对象输出/输入流联系起来,通过对象输出流将对象状态保存下来(将对象保存到文件中,或者通过网络传送到其他地方) ,再通过对象输入流将对象状态恢复。类ObjectOutputStream和ObjectInputStream分别继承了接口ObjectOutput和ObjectInput,将数据流功能扩展到可以读写对象,前者用writeObject()方法可以直接将对象保存到输出流中,而后者用readObject()方法可以直接从输入流中读取

27、一个对象。322. 字节流例子6public class Objectser public static void main(String args) Student stu=new Student(981036, “Li Ming”, 16, “CSD”); try FileOutputStream fo = new FileOutputStream(“data.ser”); ObjectOutputStream so = new ObjectOutputStream(fo); so.writeObject(stu); so.close(); catch(Exception e) Syste

28、m.err.println(e); 332. 字节流例子6(续)public class ObjectRecov public static void main(String args) Student stu; try FileInputStream fi = new FileInputStream(“data.ser”); ObjectInputStream si = new ObjectInputStream(fi); stu = (Student)si.readObject(); si.close(); catch(Exception e) System.out.println(e);

29、 System.out.println(“ID: ”+stu.id+“name:”+ stu.name+“age:”+age+“dept.:”+stu.department); 342. 字节流对象流定制对象的串行化:在类定义中重写readObject()和WriteObject()方法。private void writeObject(ObjectOutputStream out) throws IOException out.writeInt(id); / out.defaultWriteObject()private void readObject(ObjectInputStream i

30、n) throws IOException id = in.readInt(); / out.defaultReadObject()352. 字节流对象流SerializablenExternalizablewvoid readExternal(ObjectInput in) wvoid writeExternal(ObjectOutput out) ObjectInputObjectOutput362. 字节流管道流管道用来把一个程序、线程和代码块的输出连接到另一个程序、线程和代码块的输入。java.io中提供了类PipedInputStream和PipedOutputStream作为管道的

31、输入/输出流。管道输入流作为一个通信管道的接收端,管道输出流则作为发送端。管道流必须是输入输出并用,即在使用管道前,两者必须进行连接。输出流输出流输入流输入流372. 字节流管道流管道输入/输出流可以用两种方式进行连接:n在构造方法中进行连接wPipedInputStream(PipedOutputStream pos);wPipedOutputStream(PipedInputStream pis);n通过各自的connect()方法连接w在类PipedInputStream中,connect(PipedOutputStream pos);w在类PipedOutputStream中,conn

32、ect(PipedInputStream pis);382. 字节流内存流为了支持在内存上的I/O,java.io中提供了类nByteArrayInputStreamnByteArrayOutputStreamnStringBufferInputStreamByteArrayInputStream可以从指定的字节数组中读取数据。ByteArrayOutputStream中提供了缓冲区可以存放数据(缓冲区大小可以在构造方法中设定),可以用write()方法向其中写入数据,然后用toByteArray()方法将缓冲区中的有效字节写到字节数组中去。size()方法可以知道写入的字节数;reset()

33、可以丢弃所有内容。StringBufferInputStream与ByteArrayInputStream相类似,不同点在于它是从字符缓冲区StringBuffer中读取16位的Unicode数据,而不是8位的字节数据。 (已被StringReader取代)392. 字节流内存流ByteArrayInputStreamnByteArrayInputStream(byte buf) nByteArrayInputStream(byte buf, int offset, int length) ByteArrayOutputStreamnvoid reset() :重写内容nint size()

34、:返回写入的字节数nbyte toByteArray() :以新分配的字节数组形式返回写入的内容nString toString() :以缺省字符编码方式把内容编程字符串返回nString toString(String enc) :以指定字符编码方式返回字符串nvoid writeTo(OutputStream out) :把内容写到另一个输出流中402. 字节流顺序输入流java.io中提供了类SequenceInputStream,使应用程序可以将几个输入流顺序连接起来,让程序员看起来就像是一个比较长的流一样。顺序输入流提供了将多个不同的输入流统一为一个输入流的功能,这使得程序可能变得更

35、加简洁。如:FileInputStream f1 = new FileInputStream(“file1.txt”);FileInputStream f2 = new FileInputStream(“file2.txt”);SequenceInputStream fs = new SequenceInputStream(f1, f2);FileOutputStream f3 = new FileOutputStream(“file3.txt”);copy(fs, f3);f3.close(); fs.close();413. 字符流前面说过,在JDK1.1之前,java.io包中的流只有普

36、通的字节流(以byte为基本处理单位的流),这种流对于以16位的Unicode码表示的字符流处理很不方便。从JDK1.1开始, java.io包中加入了专门用于字符流处理的类,它们是以Reader和Writer为基础派生的一系列类。同类InputStream和OutputStream一样,Reader和Writer也是抽象类,只提供了一系列用于字符流处理的接口。它们的方法与类InputStream和OutputStream类似,只不过其中的参数换成字符或字符数组。423. 字符流Readervoid close()void mark(int readAheadLimit)boolean mar

37、kSupported() :int read() int read(char cbuf) int read(char cbuf, int off, int len) boolean ready() void reset() long skip(long n) 433. 字符流Writervoid close() void flush() void write(char cbuf) void write(char cbuf, int off, int len) void write(int c) void write(String str) void write(String str, int

38、off, int len) 443. 字符流与字节流连用InputStreamReader和OutputStreamWriter是java.io包中用于处理字符流的最基本的类,用来在字节流和字符流之间作为中介。使用这两者进行字符处理时,在构造方法中应指定一定的平台规范,以便把以字节方式表示的流转换为特定平台上的字符表示。nInputStreamReader(InputStream in); /缺省规范nInputStreamReader(InputStream in, String enc); /指定规范encnOutputStreamWriter(OutputStream out); /缺省

39、规范nOutputStreamWriter(OutputStream out, String enc); /指定规范enc453. 字符流编码如果读取的字符流不是来自本地时(比如网上某处与本地编码方式不同的机器),那么在构造字符输入流时就不能简单地使用缺省编码规范,而应该指定一种统一的编码规范“ISO 8859_1”,这是一种映射到ASCII码的编码方式,能够在不同平台之间正确转换字符。nInputStreamReader ir = new InputStreamReader( is, “8859_1” );FileReader & FileWritern采用缺省编码读写字符文件n采用其它编码

40、处理字符文件时,采用 new InputStreamReader(new FileInputStream(file), “编码名”);463. 字符流缓冲同样的,为了提高字符流处理的效率,java.io中也提供了缓冲流BufferedReader和BufferedWriter。其构造方法与BufferedInputStream和BufferedOutputStream相类似。另外,除了read()和write()方法外,它还提供了整行字符处理方法:public String readLine(): BufferedReader的方法,从输入流中读取一行字符,行结束标志为n、r或两者一起。pub

41、lic void newLine(): BufferedWriter的方法,向输出流中写入一个行结束标志,它不是简单的换行符n或r,而是系统定义的行隔离标志(line separator)。473. 字符流其它CharArrayReader & CharArrayWritern对字符数组进行处理StringReader & StringWritern对字符串进行处理FilterReader & FilterWritern过滤字符流PipedReader & PipedWritern管道字符流LineNumberReadern行处理字符输入流PrintWritern打印字符输出流484. 随机访

42、问文件File:以文件路径名的形式代表一个文件FileDescriptor:代表一个打开文件的文件描述FileFilter & FilenameFilter:用于列出满足条件的文件nFile.list(FilenameFilter fnf) nFile.listFiles(FileFilter ff)nFileDialog.setFilenameFilter(FilenameFilter fnf)FileInputStream & FileReader:顺序读文件FileOutputStream & FileWriter:顺序写文件RandomAccessFile:提供对文件的随机访问支持。4

43、94. RandomAccessFile类RandomAccessFile则允许对文件内容同时完成读和写操作,它直接继承Object,并且同时实现了接口DataInput和DataOutput,提供了支持随机文件操作的方法:nDataInput和DataOutput中的方法wreadInt(), writeDouble()nint skipBytes(int n):将指针乡下移动若干字节nlength():返回文件长度nlong getFilePointer():返回指针当前位置nvoid seek(long pos):将指针调到所需位置nvoid setLength(long newLeng

44、th):设定文件长度504. RandomAccessFileRandomAccessFile(File file, String mode) RandomAccessFile(String name, String mode) mode 的取值:n“r” 只读. 任何写操作都将抛出IOException。n“rw” 读写. 文件不存在时会创建该文件,文件存在时,原文件内容不变,通过写操作改变文件内容。 n“rws” 同步读写. 等同于读写,但是任何协操作的内容都被直接写入物理文件,包括文件内容和文件属性。n“rwd” 数据同步读写. 等同于读写,但任何内容写操作都直接写到物理文件,对文件属性

45、内容的修改不是这样。514. RandomAccessFile例子7public static void main(String args) int data_arr=12,31,56,23,27,1,43,65,4,99; try RandomAccessFile randf =new RandomAccessFile(“temp.dat”, “rw”); for (int i=0; idata_arr.length; i+) randf.writeInt(data_arri); for (int i=data_arr.length-1; i=0; i-) randf.seek(i*4);

46、System.out.println(randf.readInt(); randf.close(); catch (IOException e) System.out.println(“File access error: “+e); 524. 文件操作FileFile(String pathname) nFile f=new File(“c:datatemp.dat”);nFile f=new File(“data temp.dat”);nFile f=new File(“temp.dat”);File(String parent, String child) nFile f=new Fil

47、e(“c:data” ,“temp.dat”);nFile f=new File(“data ” ,“ temp.dat”);File(File parent, String child) nFile f=new File(new File(“c:data”) ,“temp.dat”);nFile f=new File(new File(“data ”) ,“ temp.dat”);534. 文件操作File (1 of 4)boolean canRead() boolean canWrite() boolean setReadOnly()boolean exists() boolean is

48、Directory() boolean isFile() boolean isHidden() long lastModified() boolean setLastModified(long time)long length() 544. 文件操作File (2 of 4)String list() String list(FilenameFilter filter) File listFiles() File listFiles(FileFilter filter) File listFiles(FilenameFilter filter) static File listRoots()

49、boolean mkdir() boolean mkdirs()554. 文件操作File (3 of 4)boolean createNewFile() static File createTempFile(String prefix, String suffix) static File createTempFile(String prefix, String suffix, File directory) boolean delete() void deleteOnExit() boolean renameTo(File dest) n(粉色的方法在JDK1.2之后才支持)564. 文件

50、操作File (4 of 4)String getName() File getParentFile() String getParent() File getParentFile() String getPath() boolean isAbsolute()File getAbsoluteFile() String getAbsolutePath() File getCanonicalFile() String getCanonicalPath() 574. FileDescriptorFileInputStream & FileOutputStreamRandomAccessFilenFi

51、leDescriptor getFD() 通过FileDescriptor构造输入输出流nFileInputStream(FileDescriptor fdObj) nFileOutputStream(FileDescriptor fdObj)nFileReader(FileDescriptor fd) nFileWriter(FileDescriptor fd) 例如:nFileInputStream fin = new FileInputStream(“file.txt”);nFileReader fr = new FileReader(fin.getFD();58小结在Java中有数据传

52、输的地方都用到I/O流(通常是文件,网络,内存和标准输入输出等)。InputStream 和OutputStream是所有字节流的祖先(只有RandomAccessFile类是一个例外),read和write是它们最基本的方法,读写单位是字节。Reader 和Writer是所有字符流的祖先,read和write是它们最基本的方法,读写单位是字符。在众多的流对象中,并不是每一种都单独使用,其中过滤流的子类在数据送出去之前做必要的处理。59小结File, File(Input/Output)Stream, RandomAccessFile是处理本地文件的类。Data(Input/Output)Stream是一个过滤流的子类,借此可以读写各种基本数据,在文件和网络中经常使用。如: readByte, writeBoolean等。Buffered(Input/Output)Stream的作用是在数据送到目的之前先缓存,达到一定数量时再送到目的,已减少阻塞次数。Piped(Input/Output)Stream适合与一个处理的输出作为另一个处理的输入的情况。60下课! 61

展开阅读全文
相关资源
正为您匹配相似的精品文档
相关搜索

最新文档


当前位置:首页 > 医学/心理学 > 基础医学

电脑版 |金锄头文库版权所有
经营许可证:蜀ICP备13022795号 | 川公网安备 51140202000112号