第七章 输入输出.docx
- 文档编号:9950715
- 上传时间:2023-02-07
- 格式:DOCX
- 页数:16
- 大小:76.85KB
第七章 输入输出.docx
《第七章 输入输出.docx》由会员分享,可在线阅读,更多相关《第七章 输入输出.docx(16页珍藏版)》请在冰豆网上搜索。
第七章输入输出
教案首页
章节名称
第七章输入/输出
授课次数
第七、八课
教学目的和要求
了解流式输入输出的原理,掌握三种输入输出流的划分方法,掌握InputStream,OutputStream,Reader,Write类的常用方法,掌握FileInputStream、FileOutputStream、FileReader、FileWriter、File类、数据流类、缓冲流类、标准I/O流对象、等类的常用方法
教学重点
FileInputStream、FileOutputStream、FileReader、FileWriter、File类等与文件相关的类的常用方法
教学难点
FileInputStream、FileOutputStream、FileReader、FileWriter、File类等与文件相关的类的常用方法
教学方法和手段
讲授式和启发式相结合
专业术语
InputStream,OutputStream,Reader,Writer,separatorflush,close
教学时数
4学时
作业
主要参考资料
《Java语言程序设计》郎波,清华大学出版社
《Java程序设计教程》张小波冶金工业出版社
《Java程序设计与案例》刘宝林高等教育出版社
教学后记
第七章输入/输出
7.1流式输入输出
7.1.1流Stream的概念
1、流的概念
流:
是从源到目的的字节的有序序列。
流的特征:
先进先出、方向性
两种基本流:
InputStream(输入流)、OutputStream(输出流)
2、流操作的过程
流的读操作过程:
打开流--当流中还有数据时执行读操作--关闭流
流的写操作过程:
打开流-当数据需要输出时执行写操作--关闭流
3、流的分类
java.io包中定义了多个流类型(类或抽象类)来实现输入/输出功能;可以从不同的角度对其进行分类:
◆按数据流的方向不同,可分为输入流和输出流。
◆按相对于程序的另一端点不同,可分为节点流和过滤流。
◆按照流中数据单位不同,可分为字节流和字符流。
J2SDK所提供的所有流类型位于包java.io内都分别继承自以下四种抽象流类型:
字节流
字符流
输入流
InputStream
Reader
输出流
OutputStream
Writer
节点流和过滤流:
节点流:
从特定源如磁盘文件或内存某区域进行读或写入。
过滤流:
使用其它的流作为输入源或输出目的地。
7.1.2字节流——输入流类层次
InputStream方法:
三个基本read()方法:
intread()//读一个字节返回
intread(byte[])//将数据读入byte[],返回读的字节数
intread(byte[],intoffset,intlength)
其它方法:
voidclose()//关闭流。
自顶向下关闭Filterstream
intavailable()//返回未读的字节数
longskip(longn)//跳过n个字节
booleanmarkSupported()//测试打开的流是否支持标记
voidmark(int)//标记当前流,并建立int大小缓冲区
voidreset()//返回标记处
7.1.2字节流——输出流类层
OutputStream方法:
三个基本的write()方法
voidwrite(int)//写一个字节
voidwrite(byte[])//写一个字节数组
voidwrite(byte[],intoffset,intlength)
其它方法:
voidclose()
voidflush()//强行写
7.1.3字符流--Reader的类层次
Reader的基本方法
intread();//读单个字符
intread(charcbuf[]);//读字符放入数组中
intread(charcbuf[],intoffset,intlength);//读字符放入数组的指定位置
voidclose()//关闭流。
longskip(longn)//跳过n个字符
booleanmarkSupported()//测试打开的流是否支持标记
voidmark(int)//标记当前流,并建立int大小缓冲区
voidreset()//返回标记处
booleanready()//测试当前流是否准备好进行读
7.1.3字符流--Writer的类层次
Writer的基本方法
intwrite(intc);//写单个字符
intwrite(charcbuf[]);//写字符数组
intwrite(charcbuf[],intoffset,intlength);
intwrite(Stringstr);
intwrite(Stringstr,intoffset,intlength);
voidclose()
voidflush()//强行写
字节流与字符流的比较:
Reader和InputStream以及Writer与OutputStream定义的API类似,但操作的数据类型不同。
所有的流——InputStream、OutputStream、Reader、Writer在创建时自动打开;程序中可以调用close方法关闭流。
否则Java运行环境的垃圾收集器将隐含将流关闭。
例:
ByteArrayInputStream类和StringReader类的应用
importjava.io.*;
publicclassIODemo{
publicstaticvoidmain(Stringargs[])throwsIOException
{StringsrcString="ABC";
byte[]bytes=srcString.getBytes();
InputStreaminputstream=newByteArrayInputStream(bytes);
intb;
while((b=inputstream.read())>=0)
System.out.print((byte)b);
System.out.println();
inputstream.close();
Readerreader=newStringReader(srcString);
inttmp;
while((tmp=reader.read())>=0)
System.out.print((char)tmp);
reader.close();}}
7.1.6常用输入输出流类--文件流:
--FileInputStream和FileOutputStream
常用构造方法:
FileInputStream(Stringname)
FileInputStream(FilefileObj)
FileOutputStream(Stringname)
FileOutputStream(FilefileObj)throwsFileNotFoundException
常用方法:
支持其父类所提供的数据读写方法。
例:
/*顺序读取指定文件里的内容,并显示在控制台上面,直到文件结束为止。
并统计所读取字节数。
*/
//TestFileInputStream.java
importjava.io.*;
publicclassTestFileInputStream{
publicstaticvoidmain(Stringargs[]){
intb=0;
FileInputStreamin=null;
try{in=newFileInputStream("TestFileInputStream.java");
}catch(FileNotFoundExceptione){
System.out.println("找不到指定文件!
");
e.printStackTrace();}
try{longnum=0;//num用于计数
while((b=in.read())!
=-1){
System.out.print((char)b);
num++;}
in.close();
System.out.println();
System.out.println("共读取了"+num+"个字节。
");
}catch(IOExceptionioe){
System.out.println("文件读取错误!
");
ioe.printStackTrace();}}}
例:
//实现两个文件间的拷贝(注意要捕获两个异常)
importjava.io.*;
publicclassTestFileOutputStream{
publicstaticvoidmain(Stringargs[]){
intb=0;
FileInputStreamin=null;
FileOutputStreamout=null;
try{
in=newFileInputStream("E:
\\java\\TestFileOutputStream.java");
out=newFileOutputStream("E:
\\java\\copy.java");
//如指定文件不存在,则会先建立文件
while((b=in.read())!
=-1){
out.write(b);}
in.close();
out.close();
}catch(FileNotFoundExceptione){
System.out.println("找不到指定文件!
");
e.printStackTrace();
}catch(IOExceptionioe){
System.out.println("文件复制错误!
");
ioe.printStackTrace();}
System.out.println("文件复制成功!
");}}
7.1.6常用输入输出流类--文件流:
--FileReader和FileWriter
常用构造方法:
FileReader(Stringname)
FileReader(FilefileObj)throwsFileNotFoundException
FileWriter(Stringname)
FileWriter(FilefileObj)throwsIOException
常用方法:
支持其父类所提供的数据读写方法。
例:
//读取指定文件并输出(以字符为单位)
importjava.io.*;
publicclassTestFileReader{
publicstaticvoidmain(Stringargs[]){
intc=0;
FileReaderfr=null;
try{
fr=newFileReader("TestFileInputStream.java");
longln=0;
while((c=fr.read())!
=-1){
System.out.print((char)c);
ln++;}
fr.close();
System.out.println();
System.out.println("共读取了"+ln+"个字符。
");
}catch(FileNotFoundExceptione){
System.out.println("找不到指定文件!
");
e.printStackTrace();
}catch(IOExceptionioe){
System.out.println("文件读取错误!
");
ioe.printStackTrace();}}}
7.1.6常用输入输出流类–缓存流
是过滤流。
数据从原始流成块读入或将数据积累到一个大数据块后再成批输出。
基本方法:
intread()
intread(byte[],intoffset,intlength)
intwrite(intc)
voidwrite(byte[],intoffset,intlength)
BufferedReader增加readLine()方法。
例:
importjava.io.*;
publicclassTestBufferStream{
publicstaticvoidmain(Stringargs[])throwsIOException{
Strings;
FileInputStreamfis=newFileInputStream(
"e:
\\java\\TestBufferStream.java");
InputStreamReaderir=newInputStreamReader(fis);
BufferedReaderin=newBufferedReader(ir);
while((s=in.readLine())!
=null){
System.out.println("Read:
"+s);}
in.close();
ir.close();
fis.close();}}
7.1.6常用输入输出流类—数据流DataInputStream和DataOutputStream(Filterstream)
读写基本数据类型:
DataInputStream方法
bytereadByte()booleanreadBoolean()
longreadLong()charreadChar()
doublereadDouble()floatreadFloat()
shortreadshort()intreadInt()
DataOutputStream方法
voidwriteByte(byte)voidwriteBoolean(boolean)
voidwriteLong(long)voidwriteChar(char)
voidwriteDouble(double)voidwriteFloat(float)
voidwriteshort(short)voidwriteInt(int)
voidwriteBytes(String)voidwriteChars(String)
示例:
importjava.io.*;
publicclassDataIOTest{
publicstaticvoidmain(String[]args)throwsIOException{
//writethedataout
DataOutputStreamout=newDataOutputStream(new
FileOutputStream("invoice1.txt"));
double[]prices={19.99,9.99,15.99,3.99,4.99};
int[]units={12,8,13,29,50};
String[]descs={"JavaT-shirt","JavaMug","DukeJugglingDolls",
"JavaPin","JavaKeyChain"};
for(inti=0;i out.writeDouble(prices[i]); out.writeChar('\t'); out.writeInt(units[i]); out.writeChar('\t'); out.writeChars(descs[i]); out.writeChar('\n');} out.close(); //readitinagain DataInputStreamin=newDataInputStream(new FileInputStream("invoice1.txt")); doubleprice; intunit; Stringdesc; doubletotal=0.0; try{while(true){ price=in.readDouble(); in.readChar();//throwsoutthetab unit=in.readInt(); in.readChar();//throwsoutthetab desc=in.readLine(); System.out.println("You'veordered"+ unit+"unitsof"+ desc+"at$"+price); total=total+unit*price;} }catch(EOFExceptione){} System.out.println("ForaTOTALof: $"+total); in.close();}} 7.1.6常用输入输出流类—标准输入输出 为了支持标准的输入输出设备,Java定义了两个流的对象System.in和System.out,可以在程序中直接使用而不用重新定义自己的流对象,因为它们都是类成员。 System.out “标准”输出流 //把输出送到缺省的显示(通常是显示器); //它是PrintStream类的对象; //有print()和println()等方法实现输出 System.in “标准”输入流 //从标准输入获取输入(通常是键盘) //它是InputStream类的对象; //有read()方法实现输入 System.err “标准”错误输出流 //把错误信息送到缺省的显示 例: importjava.io.*; publicclassStandardIO{ publicstaticvoidmain(String[]args){ Strings; BufferedReaderin=newBufferedReader(newInputStreamReader(System.in)); System.out.println("Pleaseinput: "); try{s=in.readLine(); while(! s.equals("exit")){ System.out.println("read: "+s); s=in.readLine();} System.out.println("EndofInputting."); in.close(); }catch(IOExceptione){ e.printStackTrace();}}} 7.2文件 7.2.1创建文件对象 java.io.File: 是外存文件或目录的抽象表示。 它不是一个流类,用来管理磁盘文件和目录。 ●构造方法: File(Stringpathname) //将pathname字符串转换成一个抽象的路径名,创建File对象 File(Stringpath,Stringname) //从一个父路径名称字符串和文件或目录名称字符串构造文件对象 File(Filedir,Stringname) //从dirt表示的路径名和name表示的文件名构造文件对象 ●常量(static类型): separator、separatorChar当前系统的目录分割符(\) pathSeparator、pathSeparatorChar路径分隔符(;) 7.2.2操作文件对象 文件名: StringgetName() StringgetPath() StringgetAbsolutePath() StringgetParent() booleanrenameTo(FilenewName) 文件测试: booleanexists() booleancanWrite() booleancanRead() booleanisFile() booleanisDirectory() booleanisAbsolute() 7.3随机存取文件 在java中,类RandomAccessFile提供了随机访问文件的方法。 ●类RandomAccessFile的声明为: publicclassRandomAccessFileextendsObject implementsDataInput,DataOutput ●接口DataInput中定义的方法主要包括从流中读取基本类型的数据、读取一行数据、或者读取指定长度的字节数。 如: readBoolean()、readInt()、readLine()、readFully()等。 ●接口DataOutput中定义的方法主要是向流中写入基本类型的数据、或者写入一定长度的字节数组。 如: writeChar()、writeDouble()、write()等。 ●构造函数: RandomAccessFile(Stringname,Stringmode); //name是文件名,mode是打开方式,如“r”,"rw" RandomAccessFile(Filefile,Stringmode); //file是文件对象,如文件不存在则自动创建 ●文件的操作方法: longgetFilePointer();//得到当前的文件指针 voidseek(longpos);//移动文件指针到指定位置 read(); write(); 例: importjava.io.*; publicclasstestaccessfile {publicstaticvoidmain(Stringargs[])throwsException {RandomAccessFilef=newRandomAccessFile(
- 配套讲稿:
如PPT文件的首页显示word图标,表示该PPT已包含配套word讲稿。双击word图标可打开word文档。
- 特殊限制:
部分文档作品中含有的国旗、国徽等图片,仅作为作品整体效果示例展示,禁止商用。设计者仅对作品中独创性部分享有著作权。
- 关 键 词:
- 第七章 输入输出 第七