Java程序设计案例教程课件第9章_第1页
Java程序设计案例教程课件第9章_第2页
Java程序设计案例教程课件第9章_第3页
Java程序设计案例教程课件第9章_第4页
Java程序设计案例教程课件第9章_第5页
已阅读5页,还剩36页未读 继续免费阅读

下载本文档

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

文档简介

程序设计第9章输入与输出2目录

9.1数据流的基本概念

9.2字节输入/输出流

9.3字符输入/输出流9.4文件处理

9.5对象串行化39.1数据流的基本概念I/O处理用流来表示内存外设

(硬盘)流(管道)输入流(读入)输出流(写出)49.1.1输入/输出流输入输出流的分类按流的方向分类输入流输出流按流处理的数据单位不同分类字节流字符流按流的功能不同分类节点流处理流9.1.2输入/输出类输入输出流有关的类Java语言提供的与I/O流有关的类多达数十种,它们分为四大类字节输入流InputStream字节输出流OutputStream字符输入流Reader字符输出流Writer569.2字节输入/输出流以字节为单位对数据进行处理字节输入流从外设(硬盘)读取数据read()方法字节输出流将数据写出到外设(硬盘)write()方法适用于处理二进制文件可执行文件:*.exe、*.dll等图片图像文件:*.gif、*.jpg等特定格式的文件:*.doc、*.pdf等7FileInputStream类(1)FileInputStream类的构造方法通过文件file对象来创建一个FileInputStream对象publicFileInputStream(Filefile)throwsFileNotFoundException通过文件名为name的文件来创建一个FileInputStream对象publicFileInputStream(Stringname)throwsFileNotFoundException如果指定的文件不存在,或者因为其他原因无法进行文件读取,则会抛出FileNotFoundException的异常。FileInputStream类(2)FileInputStream类的Read()方法从输入流中读取一个数据字节。如果已到达文件末尾,返回-1。publicint

read()throwsIOException从输入流中将最多b.length个字节的数据读入到byte数组中。如果已到达文件末尾,返回-1。publicint

read(byte[]b)throwsIOException对于这两个read()方法,如果读取文件时发生错误,则会抛出IOException的异常。8FileOutputStream类(1)FileOutputStream类的构造方法创建一个指向file文件中写入字节数据的FileOutputStream对象publicFileOutputStream(Filefile)throwsFileNotFoundException创建一个指向File文件中写入字节数据的FileOutputStream对象,且如果第2个参数为true,则将字节数据追加到文件末尾处,否则将字节数据写入文件开始处覆盖原有的文件publicFileOutputStream(File

file,booleanappend)throwsFileNotFoundException创建一个向具体指定名称为name的文件中写入字节数据的FileOutputStream对象publicFileOutputStream(Stringname)throwsFileNotFoundException创建一个向具体指定名称为name的文件中写入字节数据的FileOutputStream对象,且如果第2个参数为true,则将字节数据追加到文件末尾处,否则将字节数据写入文件开始处覆盖原有的文件publicFileOutputStream(String

name,booleanappend)throwsFileNotFoundException

对于这四个构造方法,如果指定的文件不存在,或者因为其他原因无法进行文件写入,则会抛出FileNotFoundException的异常。9FileOutputStream类(2)FileOutputStream类的Write()方法将指定字节写入文件输出流。write的常规协定是向输出流写入一个字节,要写入的字节是参数b的8个低位。publicvoidwrite(int

b)throws

IOException将b.length个字节从byte数组写入文件输出流中。publicvoidwrite(byte[]b)throwsIOException对于这两个write()方法,如果写入文件时发生错误,则会抛出IOException的异常。1011操作步骤

FileInputStream

fis=null;//声明一个流。

fis=newFileInputStream("E:/filename.txt");//打开文件

intb;

b=fis.read();//读入一个字节

System.out.print((char)b);

//输出到屏幕上

fis.close();

System.out.println("\n文件读出完成.");12异常处理publicclassFileInputDemo{ publicstaticvoidmain(String[]args){

intb;

FileInputStream

fis=null; try{

fis=newFileInputStream("E:\\test.txt");

while((b=fis.read())!=-1){

System.out.print((char)b); } }catch(FileNotFoundExceptione){

System.out.println("找不到文件!"); }catch(IOExceptione){

System.out.println("文件读写错误!"); }finally{ if(fis!=null){ try{

fis.close(); }catch(IOExceptione){

System.out.println("文件无法关闭!"); } } } }}一次读取多个字节publicclassFileInputDemo{ publicstaticvoidmain(String[]args){

byte[]b=newbyte[80];

StringBufferbuffer=newStringBuffer();

intcount;

FileInputStream

fis=null; try{

fis=newFileInputStream("E:\\test.txt");

while((count=fis.read(b))!=-1){

buffer.append(newString(b,0,count)); }

System.out.println(buffer); }catch(FileNotFoundExceptione){

System.out.println("找不到文件!"); }catch(IOExceptione){

System.out.println("文件读写错误!"); }finally{ if(fis!=null){ try{

fis.close(); }catch(IOExceptione){

System.out.println("文件无法关闭!"); } } } }}1314写到文件中write()方法,有多个重载写字节数组写一个字节publicclassFileInputDemo{ publicstaticvoidmain(String[]args){ byteb1[]={'a','b','c'};//将被写到文件中的字节数组

byteb2='A';//将被写到文件中的字节

FileOutputStream

fos=null; try{

fos=newFileOutputStream("E:\\filename.txt"); fos.write(b1);//写字节数组

fos.write(b2);//写字节

}catch(Exceptione){

System.out.print("写文件出错"); }finally{ try{

fos.close(); }catch(IOExceptione){

e.printStackTrace(); } } }}【例9.2】通过字节流读取与写入的方式,实现文件复制的功能(将d:\mytest.jpg复制到e:\mycopy.jpg文件中)。 publicstaticvoidmain(String[]args){

FileInputStream

fis=null; //声明字节输入流

FileOutputStream

fos=null; //声明字节输出流

try{

fis=newFileInputStream("d:/mytest.jpg");

fos=newFileOutputStream("e:/mycopy.jpg");

intb; while((b=fis.read())!=-1){ //从输入流读入

fos.write((byte)b); //写出到输出流中

}

}catch(FileNotFoundExceptione){ //以下是异常处理

System.out.print("文件找不到或文件权限不够异常.");

e.printStackTrace(); }catch(IOExceptione){

System.out.print("读或写文件异常.");

e.printStackTrace(); }finally{ //finally语句块

if(fis!=null){ try{

fis.close(); //关闭输入流

}catch(IOExceptione){

System.out.print("文件无法关闭异常.");

e.printStackTrace(); } } if(fos!=null){ try{

fos.close(); //关闭输出流

}catch(IOExceptione){

System.out.print("文件无法关闭异常.");

e.printStackTrace(); } } }

System.out.println("\n文件复制完成."); }159.2.2过滤流需要进行特殊数据的输入/输出:过滤流DataInputStream类和DataOutputStream类可以读/写各种JAVA语言的数据类型【例9.3】通过过滤流读取与写入的方式,实现包含中文字符的文件的读写功能。

FileOutputStream

fos=null;DataOutputStreamdos=null;String[]s={"您好","欢迎光临!"};try{//创建文件输出字节流

fos=newFileOutputStream("d:/test.txt");//创建二进制数据输出流

dos=newDataOutputStream(fos);

for(String

j:s){//通过writeUTF写入文件

dos.writeUTF(j);}//更新数据流

dos.flush();17【例9.3】通过过滤流读取与写入的方式,实现包含中文字符的文件的读写功能。

DataInputStream

dis=null;

DataOutputStreamdos=null;//创建文件输入字节流is=newFileInputStream("d:/test.txt");//创建二进制数据输入流

dis=newDataInputStream(is);//判断读取的流是否有效

while(dis.available()>0){//通过writeUTF读取文件Stringk=dis.readUTF();

System.out.print(k+"");}1819缓冲流缓冲流是一种过滤流可以写成一行输入流输出流内存外设

(硬盘)过滤流FileInputStreamBufferedInputStream

FileInputStream

fis;

fis=newFileInputStream("filename");

BufferedInputStream

bis;

bis=newBufferedInputStream(fis);

BufferedInputStream

bis=newBufferedInputStream(new

FileInputStream("filename"));BufferedOutputStream

bos=newBufferedOutputStream(new

FileOutputStream("filename"));20缓冲流BufferedInputStream类和BufferedOutputStream类直接处理大文件时,效率是非常低的使用缓冲技术可以提高效率

intb=0;

FileInputStream

fis;

fis=newFileInputStream("filename");

BufferedInputStream

bis;

bis=newBufferedInputStream(fis);while((b=bis.read())!=-1){

System.out.print((char)b);}

bis.close();

intb=0;

FileInputStream

fis;

fis=newFileInputStream("filename");while((b=fis.read())!=-1){//每次读入一个字节,返回-1表示没有内容可读

System.out.print((char)b);//输出到屏幕上}

fis.close();【例9.4】通过BufferedInputStream类和BufferedOutputStream类对【例9.2】进行改进。

FileInputStream

fis=null; //声明字节输入流

FileOutputStream

fos=null;//声明字节输出流

BufferedInputStream

bis=null; //声明缓冲输入流

BufferedOutputStream

bos=null; //声明缓冲输出流 try{

bis=newBufferedInputStream(new

FileInputStream(("d:/mytest.jpg")));

bos=newBufferedOutputStream(new

FileOutputStream(("e:/mycopy.jpg")));

intb; while((b=bis.read())!=-1){ //其余代码不需改变,只是改为缓冲流

bos.write((byte)b); } }catch(FileNotFoundExceptione){

。。。。。21229.3字符输入/输出流以字符为单位对数据进行处理字符输入流从外设(硬盘)读取数据read()方法字符输出流将数据写出到外设(硬盘)write()方法适合处理文本文件,特别是含有Unicode码(中文)的源代码文件*.xml文件、*.html文件某些配置文件(*.properties、*.ini等)脚本文件等23字符流的有关方法字符输入流FileReader类字符输出流FileWriter类24操作步骤

FileReader

fis=null;

//声明一个流。

fis=newFileReader("E:/filename.txt");

//打开文件

intb;b=fis.read();

//读入一个字符

System.out.print(b);

//输出到屏幕上

fis.close();

System.out.println("\n文件读出完成.");比较一下(字节流)

FileInputStream

fis=null;

//声明一个流。

fis=newFileInputStream("E:/filename.txt");//打开文件

intb;

b=fis.read();//读入一个字节

System.out.print((char)b);

//输出到屏幕上

fis.close();

System.out.println("\n文件读出完成.");变量b都是int类型的,但一个用了其中的8位,一个用了其中的16位25读写文件(复制)代码中没有捕获异常的代码,但仍然使用了try结构,这是由于需要在finally中关闭流,以保证流能被关闭。这段代码所在的方法需要声明抛出异常try{

fr=newFileReader(fromFile);

fw=newFileWriter(toFile);

intb;while((b=fr.read())!=-1){//读入

fw.write(b);//写出}//复制完成}finally{//即使不捕获异常,也必须使用try...finallyif(fr!=null){

fr.close();//关闭字符输入流}if(fw!=null){

fw.close();//关闭字符输出流}}

System.out.println("\n文件复制完成.");26缓冲字符流常用方法缓冲型字符输入流缓冲型字符输出流

BufferedReader

in=newBufferedReader(new

FileReader(fileName));

BufferedWriterout=newBufferedWriter(new

FileWriter(fileName));27缓冲流的例子以文本行为单位读入源代码文件的每一行内容,输出到屏幕

staticpublicvoidprintSourceCode(Classp)throwsIOException{

BufferedReaderin=null;Stringpath=System.getProperty("user.dir");//获得当前工作目录Stringname=p.getName();//获得类的全限定名name=name.replace('.','/');//将点分隔符替换为路径分隔符StringfileName=path+"/src/"+name+".java";//src是Eclipse的源码路径

System.out.println("源代码文件:"+fileName);try{in=newBufferedReader(new

FileReader(fileName));Stringstr=null;while((str=in.readLine())!=null){//每次读入一行

System.out.println(str);}

}finally{if(in!=null){try{

in.close();

}}}}printSourceCode(InputDemo.class);28注意事项结束时要关闭流,并且关闭的代码应该放在finally语句块中。使用缓冲流可以大幅度提高性能。使用各种过滤流来完成特定的功能,如加密和解密。299.4文件处理9.1.1文件处理概述文件处理文件操作目录操作:是一种特殊的文件File类平台无关性对Linux和Windows平台,使用相同的File类Windows文件系统Linux文件系统30文件类的使用File类描述了文件对象的属性和提供了对文件对象的操作。31一些常用的操作获得文件或目录的信息判断文件或目录是否存在

Filefile=newFile("D:/eclipse/eclipse.exe");

System.out.println(file.exists());//true,文件存在

System.out.println(file.length());//57344

System.out.println(file.getPath());//D:\eclipse\eclipse.exe

System.out.println(file.getParent());//D:\eclipse

System.out.println(file.getName());//eclipse.exe

System.out.println(file.isDirectory());//false

System.out.println(file.isFile());

//true

if(!new

File("D:/eclipse/eclipse.exe").exists()){

System.out.println("文件eclipse.exe找不到.");}32一些常用的操作(二)删除文件或目录删除失败的可能原因有:要删除的文件或目录不存在。要删除的是一个目录,而该目录下还有文件或目录。没有权限进行删除操作。创建目录

if(new

File("D:/doc/myfile.txt").delete()){

System.out.println("删除成功.");}else{

System.out.println("删除失败.");}newFile(“D:/docs/mydoc”).mkdir();//如果目录docs不存在,则创建失败newFile("D:/docs/mydoc").mkdirs();//如果目录docs不存在也将被创建33列出一个目录下的所有文件使用listFiles()方法返回的是File数组使用list()方法返回的是String数组

Filefile=newFile("c:/windows");String[]fileName=file.list();

System.out.println("共有"+fileName.length+"个文件和目录。");

for(inti=0;i<fileName.length;i++){

System.out.println(fileName[i]);}

Filefile=newFile("c:/windows");File[]files=file.listFiles();

System.out.println("共有"+files.length+"个文件和目录。");

for(inti=0;i<files.length;i++){

System.out.println(files[i].getName());}34列出一个目录及其子目录下的所有文件通过递归调用实现

publicstaticvoidmain(String[]args){Stringpath=System.getProperty("user.dir");//取得当前目录Filefile=newFile(path);

listAll(file);}

publicstaticvoidlistAll(Filedir){//递归列出目录和文件if(dir.isDirectory()){

System.out.println("==目录:"+dir.getName());}else{

System.out.println("文件名:"+dir.getName());}if(dir.isDirectory()){//如果是目录,列出子目录的内容String[]children=dir.list();for(inti=0;i<children.length;i++){

listAll(new

File(dir,children[i]));//直接递归调用}}}35文件名过滤器listFiles()方法和list()方法有一个重载,可以指定文件名过滤器文件名过滤器需要自定义,它必须实现FilenameFilter接口classFilterimplementsFilenameFilter{//实现文件名过滤器StringextName;

//扩展名

Filter(Stringextent){

//构造方法初始化扩展名的设置

this.extName=extent;}publicboolean

accept(Filedir,Stringname){returnname.endsWith("."+extName);//满足扩展名要求,则返回true}}Filterfilter=newFilter("exe");

Stringfiles[]=dir.list(filter);369.5对象的串行化串行化(序列化)作用是将对象的状态保存下来因此也称为持续性(持久性)串行化的用途:将对象保存到文件中,需要时再读取出来。程序运行时通过网络传输对象。37声明可串行化的类只有实现

温馨提示

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

评论

0/150

提交评论