版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领
文档简介
1、1,第6章 输入/输出流和文件,郑莉,JAVA语言程序设计,2,内容,输入/输出流 I/O 流的概念 I/O流类概述 字符流Reader和 Writer类 二进制数据流InputStream和 OutputStream类 系统IO流,文件读写 读文本文件 写文本文件 读二进制文件 写二进制文件 处理压缩文件 对象序列化 File类,3,Java中的IO,Java语言中没有标准的IO语句。 采用IO包中的方法实现IO。,IO 流的概念,4,IO 流,输入流 输出流,IO 流的概念,5,源和目标的类型,IO 流的概念,6,流的类型,流对象可以是: 输入流或输出流 处理流或普通流 面向字符的流或面向
2、字节的流,IO 流的概念,7,IO 流类概述,8,流的分类,面向字节的流. 用于一般目的的输入输出. 数据可以是基本数据类型或者原生字节( raw bytes ) 源和目标通常为文本文件 面向字符的流. 专门用来处理字符数据. 将Java程序中16位char与外部使用的UTF格式进行转换。,IO 流类概述,9,字符流,10,内部和外部格式,字符流可以实现Java程序中的内部格式和文本文件中的外部格式之间转换 内部格式 16-bit char 数据类型 外部格式 UTF指:Universal character set Transformation Format。很多人称之为Universal
3、Text Format 不仅包括ASCII 码而且包括非ASCII 码字符,比如: 斯拉夫(Cyrillic)字符, 希腊字符,亚洲字符等。,字 符 流,11,Readers,字 符 流,12,Writers,字 符 流,13,字节流,14,InputStream,字 节 流,15,OutputStream,字 节 流,16,FileInputStream/FileOutputStream,FileInputStream 从文件读取字节。 Fileoutputstream 向文件写入字节数据。,字 节 流,17,标准 I/O,标准输入 标准输出 标准错误输出,18,System IO Stre
4、am,System类中包括一些有用的类成员变量和方法。 System.in 输入流 System.out 用于输出普通结果的输出流。 System.err 用于输出错误信息的输出流。,标准 I/O,19,从标准输入流读取,System.in 是原始InputStream. 首先要经过包装才能从中读取信息。 import java.io.*; public class Echo public static void main(String args) throws IOException BufferedReader in = new BufferedReader( new InputStrea
5、mReader(System.in); String s; while(s = in.readLine().length() != 0) System.out.println(s); ,标准 I/O,20,BufferedReader,import java.io.*; class Echo public static void main (String args) throws IOException InputStreamReader inStream = new InputStreamReader( System.in ) ; BufferedReader stdin = new Buf
6、feredReader( inStream ); System.out.println(Enter the data:); String inData = stdin.readLine(); System.out.println(You entered: + inData ); ,标准 I/O,21,流的处理,用一行表达式实现: BufferedReader stdin = new BufferedReader( new InputStreamReader( System.in ) );,标准 I/O,22,将System.out 转换成 PrintWriter,import java.io.
7、*; public class ChangeSystemOut public static void main(String args) PrintWriter out = new PrintWriter(System.out, true); out.println(Hello, world); ,标准 I/O,23,PrintWriter,System.out 是一个 PrintStream。 PrintWriter将对象的格式化表示形式输出到文本输出流。 这个类实现了PrintStream 具有的所有输出方法,但是与PrintStream 类不同,如果automatic flushing为
8、真,只有当调用 println() 时缓冲区才被写并清空,不像PrintStream 遇到换行符便清空缓冲区。 println() 方法是用平台自己的换行标记,而不是换行符。,标准 I/O,24,标准I/O 重导向(Redirecting),setIn(InputStream) setOut(PrintStream) setErr(PrintStream),标准 I/O,import java.io.*; public class Redirecting public static void main(String args) throws IOException BufferedInputS
9、tream in = new BufferedInputStream( new FileInputStream( Redirecting.java); PrintStream out = new PrintStream( new BufferedOutputStream( new FileOutputStream(test.out); System.setIn(in); System.setOut(out); System.setErr(out);,BufferedReader br = new BufferedReader( new InputStreamReader(System.in);
10、 String s; while(s = br.readLine() != null) System.out.println(s); out.close(); / Remember this! ,27,过滤流 (filter stream),从流读写数据的同时对数据进行处理。 基于另一个流来构造过滤流。,28,使用过滤流,构造过滤流时,把它连接到另一个输入(或输出)流上: BufferedReader d = new BufferedReader(new DataInputStream(System.in);,29,例子输入整数,import java.io.*; class EchoSqua
11、re public static void main (String args) throws IOException BufferedReader stdin = new BufferedReader ( new InputStreamReader( System.in ) ); System.out.println(Enter an integer:); String inData = stdin.readLine(); int num = Integer.parseInt( inData ); / convert inData to int / =(new Integer(in.read
12、Line().intValue(); int square = num * num ; / compute the square System.out.println(The square of + inData + is + square ); ,30,对象流,ObjectInputStream 从来源(source)读取一个对象. ObjectOutputStream 把对象写到磁盘.,31,写文本文件,FileWriter类 创建一个磁盘文件 关闭一个磁盘文件 write() 方法 捕获 IO 异常 BufferedWriter 类,32,Writer,33,FileWriter 流举例
13、,import java.io.*; /ex6_1 class WriteTextFile public static void main ( String args ) throws IOException String fileName = reaper.txt ; FileWriter writer = new FileWriter( fileName ); writer.write( Behold her, single in the field,n); writer.write( Yon solitary Highland Lass!n ); writer.write( Reapin
14、g and singing by herself;n ); writer.write( Stop here, or gently pass!n ); writer.close(); ,34,字符集转换,35,FileWriter 的构造方法,public static void main ( String args ) throws IOException String fileName = reaper.txt ; FileWriter writer = new FileWriter( fileName ); Constructor: FileWriter(String fileName)
15、FileWriter(String fileName, boolean append),36,IOExceptions,多数IO方法在遇到错误时抛出异常,调用这些方法的方法必须作如下事情: 在函数头声明抛出IOException异常 在try块中执行IO,然后捕获IOException,37,举例,import java.io.*; /ex6_2 class WriteTextFile2 public static void main ( String args ) String fileName = reaper.txt ; try FileWriter writer = new FileW
16、riter( fileName, true ); writer.write( Alone she cuts and binds the grain,n ); writer.write( And sings a melancholy strain;n ); writer.write( O listen! for the Vale profoundn ); writer.write( Is overflowing with the sound.nn ); writer.close(); catch ( IOException iox ) System.out.println(Problem wri
17、ting + fileName ); ,38,BufferedWriter 流,一种更有效的方式 BufferedWriter out = new BufferedWriter(new FileWriter(stuff.txt); BufferedWriter除与FileWriter有同样的方法外,还增加了一个方法: newLine()不同厂家生产的计算机 (IBM, Apple, VAX, Sun) 对文字的换行方法不同。newLine()方法可以输出在当前计算机上正确的换行符。,39,更新后的例子,import java.io.*; /ex6_3 class WriteTextFile3
18、public static void main ( String args ) String fileName = reaper.txt ; try BufferedWriter out = new BufferedWriter( new FileWriter( fileName ) ); out.write( No Nightingale did ever chaunt ); out.newLine() ; out.write( More welcome notes to weary bands ); out.newLine() ; out.write( Of travellers in s
19、ome shady haunt, ); out.newLine() ; out.write( Among Arabian sands. ); out.newLine() ; out.close(); catch ( IOException iox ) System.out.println(Problem writing + fileName ); ,40,读文本文件,Reader FileReader 和 BufferedReader readLine() 文本文件复制,41,Reader 流,42,FileReader 和 BufferedReader,我们熟悉的,用于键盘输入的方法: Bu
20、fferedReader stdin = new BufferedReader(new InputStreamReader( System.in ); 文件输入方法: BufferedReader in = new BufferedReader(new FileReader( fileName ) );,43,举例,import java.io.*; class ex6_4 public static void main ( String args ) String fileName = reaper.txt ; String line;,try BufferedReader in = new
21、 BufferedReader(new FileReader( fileName ) ); line = in.readLine(); while ( line != null ) / continue until end of file System.out.println( line ); line = in.readLine(); in.close(); catch ( IOException iox ) System.out.println(Problem reading + fileName ); ,45,文本文件复制程序,java copy sourceFile destinati
22、onFile,46,完整的程序,import java.io.*; /ex6_5 class CopyMaker String sourceName, destName; BufferedReader source; BufferedWriter dest; String line;,private boolean openFiles() try source = new BufferedReader(new FileReader( sourceName ); catch ( IOException iox ) System.out.println(Problem opening + sour
23、ceName ); return false; try dest = new BufferedWriter(new FileWriter( destName ); catch ( IOException iox ) System.out.println(Problem opening + destName ); return false; return true; ,private boolean copyFiles() try line = source.readLine(); while ( line != null ) dest.write(line); dest.newLine();
24、line = source.readLine(); catch ( IOException iox ) System.out.println(Problem reading or writing ); return false; return true; ,private boolean closeFiles() boolean retVal=true; try source.close(); catch ( IOException iox ) System.out.println(Problem closing + sourceName ); retVal = false; try dest
25、.close(); catch ( IOException iox ) System.out.println(Problem closing + destName ); retVal = false; return retVal; ,public boolean copy(String src, String dst ) sourceName = src ; destName = dst ; return openFiles() ,51,写二进制文件,二进制文件 OutputStream FileOutputStream BufferedOutputStream DataOutputStrea
26、m writeInt() writeDouble() writeBytes() Hexadecimal file dumps.,52,二进制文件,原则上讲,所有文件都是由8位的字节组成的 如果文件字节中的内容应被解释为字符,则文件被称为文本文件;如果被解释为其它含义,则文件被称为二进制文件。 文字处理程序产生的文件中,数据要被解释为字体、格式、图形和其他非字符信息。因此,这样的文件是二进制文件,不能用Reader流正确读取。,53,OutputStream,OutputStream是一个抽象类。 FileOutputStream是OutputStream的派生类 用于一般目的输出(非字符输出)
27、 用于成组字节输出 对于基本数据类型,在各平台上输出的格式是相同的,二进制文件中的数据可以被运行在任何平台上的Java程序正确读取,54,举例,import java.io.*; /ex6_6 class WriteInts public static void main ( String args ) String fileName = intData.dat ; int value0 = 0, value1 = 1, value255 = 255, valueM1 = -1;,try /将FileOutputStream与DataOuputStream连接 /可以输出不同类型的数据 Dat
28、aOutputStream out = new DataOutputStream(new FileOutputStream( fileName ) ); out.writeInt( value0 ); out.writeInt( value1 ); out.writeInt( value255 ); out.writeInt( valueM1 ); out.close(); catch ( IOException iox ) System.out.println(Problem writing + fileName ); ,56,BufferedOutputStream,DataOutputS
29、tream out = new DataOutputStream( new BufferedOutputStream( new FileOutputStream( fileName ) ) );,57,writeDouble(),import java.io.*; /ex6_7 class WriteDoubles public static void main ( String args ) throws IOException String fileName = doubleData.dat ; DataOutputStream out = new DataOutputStream( ne
30、w BufferedOutputStream( new FileOutputStream( fileName ) ) ); out.writeDouble( 0.0 ); out.writeDouble( 1.0 ); out.writeDouble( 255.0 ); out.writeDouble( -1.0 ); out.close(); ,58,DataOutputStream,DataOutputStream 用于基本类型的数据字节 它将数据写到另一个输出流。 它在所有的计算机平台上使用同样的数据格式,59,DataOutputStream 方法,public DataOutputS
31、tream(OutputStream out) public void flush() public final int size() public void write(int b) public final void writeBoolean(boolean b) public final void writeByte(int b) public void writeBytes(String s) public final void writeChar(int c) public void writeDouble(double v) public void writeFloat(float
32、 f) public void writeInt(int i) public void writeLong(long l) public final void writeShort(int s),60,字节计数器,import java.io.*; /ex6_8 class ByteCounter public static void main ( String args ) throws IOException String fileName = mixedTypes.dat ; DataOutputStream dataOut = new DataOutputStream( new Buf
33、feredOutputStream( new FileOutputStream( fileName ) ) ); dataOut.writeInt( 0 ); System.out.println( dataOut.size() + bytes have been written.); dataOut.writeDouble( 12.45 ); /dataOut.size() 返回到目前写入的总字节数 System.out.println( dataOut.size() + bytes have been written.); dataOut.close(); ,61,原始字节,dataOut
34、.writeInt( 0 ); dataOut.writeDouble( 12.45 ); 写的数据是字节流,数据之间没有空隙或标记。程序应该知道写的是什么,将来才好利用。,62,读二进制文件,读二进制文件 二进制文件的优点 FileInputSteam FilterInputStream DataInputSteam BufferedInputSteam 读写整数 读写单字节,63,InputStream,64,为什么需要二进制文件,输入输出更快 比文本文件小很多 有些数据不容易被表示为字符,65,readInt(),import java.io.*; class ReadInts publ
35、ic static void main ( String args ) String fileName = intData.dat ; long sum = 0; try DataInputStream instr = new DataInputStream( new BufferedInputStream(new FileInputStream( fileName ) ) ); sum += instr.readInt(); sum += instr.readInt(); sum += instr.readInt(); sum += instr.readInt(); System.out.p
36、rintln( The sum is: + sum ); instr.close(); catch ( IOException iox ) System.out.println(Problem reading + fileName ); ,66,持续读取,直到遇到 EOF,try while ( true ) sum += instr.readInt(); catch ( EOFException eof ) System.out.println( The sum is: + sum ); instr.close(); ,67,另一个意外,try while ( true ) sum += i
37、nstr.readInt(); catch ( EOFException eof ) System.out.println( The sum is: + sum ); instr.close(); catch ( IOException iox ) System.out.println( Problem reading input ); instr.close(); ,68,catch 块抛出的异常,try while ( true ) sum += instr.readInt(); catch ( EOFException eof ) System.out.println( The sum
38、is: + sum ); instr.close(); / - throws IOException catch ( IOException iox )/ - this catch is for the try block /not for the previous catch block System.out.println( Problem reading input ); instr.close(); / - throws IOException ,69,嵌套的 try 块,try / other stuff goes here try while ( true ) sum += ins
39、tr.readInt(); catch ( EOFException eof ) System.out.println( The sum is: + sum ); instr.close(); catch ( IOException iox ) System.out.println( IO Problems with + fileName ); ,import java.io.*; class ReadIntEOF public static void main ( String args ) String fileName = ints.dat ; long sum = 0; try Dat
40、aInputStream instr = new DataInputStream( new BufferedInputStream(new FileInputStream(fileName); try while ( true ) sum += instr.readInt(); catch ( EOFException eof ) System.out.println( The sum is: + sum ); instr.close(); catch ( IOException iox ) System.out.println(IO Problems with + fileName ); ,
41、完整的程序,71,读写字节,DataOutputStream: public final void writeByte(int b) throws IOException /将int的最不重要字节写入输出流 DataInputStream: public final int readUnsignedByte() throws IOException /从输入流中读取1字节存入int的最不重要字节,72,文件复制程序,DataInputStream instr; DataOutputStream outstr; /. . . . try int data; while ( true ) data
42、 = instr.readUnsignedByte() ; outstr.writeByte( data ) ; catch ( EOFException eof ) outstr.close(); instr.close(); return; ,73,缓冲,DataInputStream instr; DataOutputStream outstr; /. . . . instr = new DataInputStream(new BufferedInputStream( new FileInputStream( args0 ); outstr = new DataOutputStream(
43、new BufferedOutputStream( new FileOutputStream( args1 ); try int data; while ( true ) data = instr.readUnsignedByte() ; outstr.writeByte( data ) ; catch ( EOFException eof ) outstr.close(); instr.close(); return; ,74,处理打开文件异常,DataInputStream instr; DataOutputStream outstr; /. . . . try instr = new D
44、ataInputStream( new BufferedInputStream( new FileInputStream( args0 ); outstr = new DataOutputStream( new BufferedOutputStream( new FileOutputStream( args1 ); try int data; while ( true ) data = instr.readUnsignedByte(); outstr.writeByte( data ); catch ( EOFException eof ) outstr.close(); instr.clos
45、e(); return; ,75,import java.io.*; /ex6_10 class CopyBytes public static void main ( String args ) DataInputStream instr; DataOutputStream outstr; if ( args.length != 2 ) System.out.println(Please enter file names); return; ,完整的程序,try instr = new DataInputStream(new BufferedInputStream( new FileInpu
46、tStream( args0 ); outstr = new DataOutputStream(new BufferedOutputStream( new FileOutputStream( args1 ); try int data; while ( true ) data = instr.readUnsignedByte() ; outstr.writeByte( data ) ; catch ( EOFException eof ) outstr.close(); instr.close(); return; catch ( FileNotFoundException nfx ) Sys
47、tem.out.println(Problem opening files ); catch ( IOException iox ) System.out.println(IO Problems ); ,77,File 类,类 File. 构造器和方法. 路径名. 检查一个文件是否存在. 使用带有流构造器的File对象。,78,File 对象,包含文件或目录的相关信息。 它作为程序和操作系统文件处理功能之间的接口。,79,File 构造器,File( String pathName ) 为名称为pathName的文件构造一个File对象。,80,File 对象和文件,import java.i
48、o.*; class testExist /ex6_11 public static void main ( String args ) String pathName = notLikely.txt ; File test = new File( pathName ); if ( test.exists() ) System.out.println( The file + pathName + exists. ); else System.out.println ( The file + pathName + Does Not exist. ); ,81,改进的文件复制程序,import j
49、ava.io.*; /ex6_12 class CopyBytes public static void main ( String args ) DataInputStream instr; DataOutputStream outstr; if ( args.length != 2 ) System.out.println(Please Enter file names!); return; File inFile = new File( args0 ); File outFile = new File( args1 ); if ( outFile.exists() ) System.ou
50、t.println( args1 + already exists); return; if ( !inFile.exists() ) System.out.println( args0 + does not exist); return; ,try instr = new DataInputStream(new BufferedInputStream( new FileInputStream( inFile ); outstr = new DataOutputStream(new BufferedOutputStream( new FileOutputStream( outFile ); t
51、ry int data; while ( true ) data = instr.readUnsignedByte() ; outstr.writeByte( data ) ; catch ( EOFException eof ) outstr.close(); instr.close(); return; catch ( FileNotFoundException nfx ) System.out.println(Problem opening files ); catch ( IOException iox ) System.out.println(IO Problems ); ,83,串
52、连文件,利用SequenceInputStream 类,从多个输入源建立一个输入流。 构造函数原型 SequenceInputStream(Enumeration e) 参数e必须是集合类型,集合中产生的元素必须是InputStream类型。 SequenceInputStream(InputStream s1, InputStream s2),84,举例,利用SequenceInputStream 实现文件串连功能:按照命令行参数中所列的次序将文件连接在一起。,import java.io.*; public class Concatenate public static void main
53、(String args) throws IOException ListOfFiles mylist = new ListOfFiles(args); SequenceInputStream s = new SequenceInputStream(mylist); int c; while (c = s.read() != -1) /一个文件结束时,会调用mylist. nextElement()打开下一文件 System.out.write(c); s.close(); ,import java.util.*; import java.io.*; public class ListOfFi
54、les implements Enumeration private String listOfFiles; private int current = 0; public ListOfFiles(String listOfFiles) this.listOfFiles = listOfFiles; public boolean hasMoreElements() if (current listOfFiles.length) return true; else return false; ,public Object nextElement() InputStream in = null;
55、if (!hasMoreElements() throw new NoSuchElementException(No more files.); else String nextElement = listOfFilescurrent; current+; try in = new FileInputStream(nextElement); catch (FileNotFoundException e) System.err.println(ListOfFiles: Cant open + nextElement); return in; ,88,过滤流,读或写的同时对数据进行处理。 通过另外
56、一个流来构造一个过滤流。 大部分java.io 包所提供过滤流都是的FilterInputStream和FilterOutputStream的子类。,89,FilterInputStream 和 FilterOutputStream的子类,DataInputStream 和 DataOutputStream BufferedInputStream 和 BufferedOutputStream LineNumberInputStream PushbackInputStream PrintStream,90,使用过滤流,建立过滤流的同时要在它和其他的输入或输出流之间建立连接,也就是把其他流“捆绑”
57、到过滤流上。例如: BufferedReader d = new BufferedReader(new DataInputStream(System.in); String input; while (input = d.readLine() != null) . /在此进行所需的数据处理 ,91,使用 DataInputStream 和 DataOutputStream,例子: DataIODemo 读写下面的列表数据: 19.9912Java T-shirt 9.998Java Mug 第一步 使DataOutputStream 和另一个输出流建立连接: DataOutputStream out = new DataOutputStream( new FileOutputStream(invoice1.txt);,第二步: 根据上面的格式,用DataOutputStream专门的write方法将上述发票数据写到invoice1.txt。 for (int i = 0; i prices.length; i +) out.writeDouble(pricesi); out.writeChar(t); out.writeInt(unitsi); out.writeChar(t); out.writeCh
温馨提示
- 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
- 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
- 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
- 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
- 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
- 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
- 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。
最新文档
- 磁感应强度培训
- 短路和断路课件
- 盗贼之海课件
- 2026年区块链技术应用认证分布式数据库原理测试题
- 2026年经济类英语综合能力考试题集
- 2026年建筑工程知识题库结构设计与施工工艺
- 2026年建筑工程质量验收规范模拟题
- 2026年会计职称考试财务管理专业题库及答案
- 2026年历史长河探索历史知识模拟试题集
- 2026年汽车维修技师考试题集汽车维修技能与检测
- 2026春节后复工复产安全培训第一课
- 2026湖南衡阳日报社招聘事业单位人员16人备考题库完整参考答案详解
- 2026年山东药品食品职业学院单招综合素质考试备考试题含详细答案解析
- GB/T 46878-2025二氧化碳捕集、运输和地质封存地质封存
- 2026年1月浙江省高考(首考)历史试题(含答案)
- 借款合同2026年担保协议
- 征兵体检培训课件
- 2024年河北省中考化学真题及答案解析
- 2025年职业卫生试题试题及答案
- 消毒供应室职业暴露防范
- 2025年内蒙古行政执法考试试题及答案
评论
0/150
提交评论