欢迎来到三一办公! | 帮助中心 三一办公31ppt.com(应用文档模板下载平台)
三一办公
全部分类
  • 办公文档>
  • PPT模板>
  • 建筑/施工/环境>
  • 毕业设计>
  • 工程图纸>
  • 教育教学>
  • 素材源码>
  • 生活休闲>
  • 临时分类>
  • ImageVerifierCode 换一换
    首页 三一办公 > 资源分类 > PPT文档下载  

    java第6章io流.ppt

    • 资源ID:5575456       资源大小:505.50KB        全文页数:99页
    • 资源格式: PPT        下载积分:15金币
    快捷下载 游客一键下载
    会员登录下载
    三方登录下载: 微信开放平台登录 QQ登录  
    下载资源需要15金币
    邮箱/手机:
    温馨提示:
    用户名和密码都是您填写的邮箱或者手机号,方便查询和重复下载(系统自动生成)
    支付方式: 支付宝    微信支付   
    验证码:   换一换

    加入VIP免费专享
     
    账号:
    密码:
    验证码:   换一换
      忘记密码?
        
    友情提示
    2、PDF文件下载后,可能会被浏览器默认打开,此种情况可以点击浏览器菜单,保存网页到桌面,就可以正常下载了。
    3、本站不支持迅雷下载,请使用电脑自带的IE浏览器,或者360浏览器、谷歌浏览器下载即可。
    4、本站资源下载后的文档和图纸-无水印,预览文档经过压缩,下载后原文更清晰。
    5、试题试卷类文档,如果标题没有明确说明有答案则都视为没有答案,请知晓。

    java第6章io流.ppt

    第6章 I/O:读和写,课前思考,如何读取硬盘上的某个文件内容?如何知道文件系统中有哪些目录和子目录?如何往硬盘上写文件?如何接收键盘输入?,教学目标,与外部设备和其它计算机进行交流的输入输出操作,尤其是对磁盘的文件操作,是计算机程序重要的功能,任何计算机语言都必须对输入输出提供支持。Java也不例外,它的输入输出类库中包含了丰富的系统工具,这些类被放在java.io包中。在该类库中,除了定义文件输入输出操作外,还定义了许多用来和其他外设进行信息交换的类。本章将详细介绍I/O类库中的基本内容,主要侧重于文件的输入输出管理和流的基本概念。,流,在计算机中,“流”的概念是1984年由C语言第一次引入的。“流”可以看作是一个流动的数据缓冲区,数据从数据源流向数据目的地。,I/O与流,I/O是程序设计中的重要问题,大部分的应用程序都需要I/O操作,比如从键盘获得用户输入、在屏幕输出运行结果、对磁盘文件进行读写等等。应用程序只有通过I/O操作才能实现与用户的交互及数据的处理及存储.在Java语言中,将不同类型的I/O抽象为流。所谓“流(stream)”,可以看作是数据在文件或程序之间的传递,输入流和输出流,一般来说,流有两种基本形式:输入流和输出流,根据程序是作为数据流的目的端还是源端来划分。程序首先要打开一个流,才能与数据文件进行通信。通过输入流,程序可以从数据文件读取数据,但不可向输入流中写入数据;反之,通过输出流,程序可以向数据文件中写入数据。程序与其他设备间的I/O也可以使用流,这时可将设备看作是一个数据文件。,Java I/O流类的组织模式,java.io,在Java开发环境中,主要是由包java.io中提供的一系列的类和接口来实现输入/输出处理。而标准输入/输出处理则是由包java.lang中提供的类来处理的,这些类又都是从包java.io中的类继承而来的。I/O类提供了低层次和高层次的界面。每一种介质都有一对与之相关联的输入输出类,它们提供低层次的面向数据序列(字符、字节)的界面。与介质相关的各个类都分别是输入输出抽象流类的子类,它们通常具有与介质相关的构造器及方法。I/O抽象类为所有与介质相关的具体输入输出类提供了一个统一的界面。反过来各个具体的与介质相关的输入输出类也扩展了抽象类,通过它们可以实现在具体介质上的输入输出操作,I/O操作的一般步骤,构造一个与介质相关的I/O对象,以提供一种低层次的方法将数据输入或输出到相应的介质;将与介质相关的对象强制类型转换为它的父类(即抽象I/O类),并利用该对象构造一个流对象。这样便建立起了流类对象与介质相关对象的关联;这时就可利用流对象的I/O方法进行相应介质上的数据读写。,字节流与字符流,从流中传输的数据单位分为两类:字节流从InputStream和OutputStream派生出来的一系列类,以字节(byte)为基本处理单位。字符流从Reader和Writer派生出的一系列类,以16位的Unicode码表示的字符为基本处理单位。,字节流,InputStream类,InputStream类定义了一套所有字节输入流所需的方法,OutputStream类,OutputStream类定义了一套所有字节输出流所需的方法。,字符流类,Reader与Writer类,Reader类的相关方法:void close()void mark(int readAheadLimit)boolean markSupported()int read()int read(char cbuf)int read(char cbuf,int off,int len)boolean ready()void reset()long skip(long n)Writer类的相关方法:void 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 off,int len),各种流的作用概述,各种流的作用概述,各种流的作用概述,各种流的作用概述,文件流,要对本机文件系统上的文件进行读写,需要使用文件流。Java的文件流类包括字符流的FileReader、FileWriter和字节流的FileInputStream、FileOutputStream。,Java中文件的操作,而要进行文件流操作,首先必须清楚java中关于文件的基本操作,下面我们进行详细介绍。,文件与目录的描述类File File类并不用来进行文件的读/写操作,它用来描述文件对象的属性,既可以表示文件,也可以表示目录。使用它提供的方法,我们可以得到所指对象的描述信息,包括名称、存在否、读/写权限、路径等等。,需要注意的是,当我们在Windows环境使用路径时,其分隔符不能是单一的“”符号,因为与C/C+相同,符号“”已经被转意了。例如:c:jbuilder3javabin路径是非法的,系统不会识别,正确的应该为c:jbilder3javabin 或者直接使用反斜杠/来作为路径分隔符。如c:/jbilder3/java/bin,文件描述,类File提供了一种与机器无关的方式来描述一个文件对象的属性。文件的生成public File(String path);public File(String path,String name);public File(File dir,String name);,文件描述,文件名的处理String getName();/*得到一个文件的名称(不包括路径)*/String getPath();/得到一个文件的路径名String getAbsolutePath();/*得到一个文件的绝对路径名*/String getParent();/*得到一个文件的上一级目录名*/String renameTo(File newName);/*将当前文件名更名为给定文件的完整路径*/,文件描述,文件属性测试boolean exists();/*测试当前File对象所指示的文件是否存在*/boolean canWrite();/测试当前文件是否可写boolean canRead();/测试当前文件是否可读boolean isFile();/*测试当前文件是否是文件(不是目录)*/boolean isDirectory();/*测试当前文件是否是目录*/,文件描述,普通文件信息和工具long lastModified();/*得到文件最近一次修改的时间*/long length();/得到文件的长度,以字节为单位boolean delete();/删除当前文件目录操作boolean mkdir();/*根据当前对象生成一个由该对象指定的路径*/String list();/列出当前目录下的文件,File类的方法及变量,下面我们给出几个File类的应用实例。通过例题的使用,希望对File类有更清楚的认识。例 import java.io.*;public class MyClass1 public static void main(String args)Filef=new File(c:jbuilder3myprojectsuntitled5MyClass1.java);if(!f.exists(),System.out.println(File MyClass1.java doesnt exist!);else System.out.println(This file can read+f.canRead();System.out.println(last modified+f.lastModified();System.out.println(Parent is+f.getParent();System.out.println(File length is+f.length();public MyClass1(),图 7.3,例 import java.io.*;class FileTestpublic static void main(String args)System.out.println(path separator+File.pathSeparator);System.out.println(path separator char+File.pathSeparatorChar);System.out.println(separator+File.separator);System.out.println(separator char+File.separatorChar);File f=new File(/dong1/test1.class);();System.out.println(f);System.out.println(exist?+f.exists();,System.out.println(name+f.getName();System.out.println(path+f.getPath();System.out.println(absolute path+f.getAbsolutePath();System.out.println(parent+f.getParent();System.out.println(is a file?+f.isFile();System.out.println(is a directory?+f.isDirectory();System.out.println(length+f.length();System.out.println(can read+f.canRead();System.out.println(can write+f.canWrite();System.out.println(last modified+f.lastModified();,File newF=new File(newFile);(.Rename+f+.);f.renameTo(newF);System.out.println(name+newF.getName();System.out.println(f+exist?+f.exists();(.delete+newF+.);newF.delete();System.out.println(newF+exist?+newF.exists();,运行结果,path separator:path separator char:separator/separator char/dong1/test1.classexist?truename test1.classpath/dong1/test1.classabsolute path/dong1/test1.classparent/dong1,运行结果,is a file?trueis a directory?falselength 514can read truecan write truelast modified 907117020000.Rename/dong1/test1.classname newFile/dong1/test1.class exist?false.delete newFile.newFile exist?false,文件夹处理,list方法用于列出一个目录中所有的文件或与某个模式相匹配的文件。列出目录中与某种模式相匹配的文件:public String list(FilenameFilter filter);在接口 FilenameFilter中定义的方法只有:boolean accept(File dir,String name);,例:import java.io.*;public class FileFilterTestpublic static void main(String args)File dir=new File(“/dongl”);Filter filter=new Filter(“htm”);System.out.println(“list html files in directory”+dir);String files=dir.list(filter);,for(int i=0;ifiles.length;i+)File f=new File(filesi);if(f.isFile()System.out.println(“file”+f);elseSystem.out.println(“sub directory”+f);,class Filter implements FilenameFilterString extent;Filter(String extent)this.extent=extent;public boolean accept(File dir,String name)return name.endsWith(“.”+extent);,运行结果,list html files in directoty/donglfile cert_test.htmfile cert_sample.htmfile cert_obj.htm,例import java.io.*;public class MyClass2 public static void main(String args)File f1=new File(c:jbuilder3myprojects);if(!f1.isDirectory()System.out.println(Error:+f1+isnt a directory!);else String dirList=f1.list();for(int i=0;idirList.length;i+)System.out.println(dirListi);public MyClass2(),在该例中,我们并没有在调用File类的list方法中传递参数,这样,处在目录c:jbuilder3myprojects下的所有文件及目录将均被输出,结果如图7.4所示。,图 7.4,1Byte流(字节流)文件的读取 该类的结构如图7.1所示,我们主要用其中的FileOutputStream和FileInputStream类,它们的父类为InputStream和OutputStream。主要的方法有:InputStream int read()int read(byte buf)int read(byte buf,int offset,int length)close(),利用流进行文件I/O处理,OutputStreamint write(int c)int write(byte buf)int write(byte buf,int offset,int length)close()下面给出一个应用实例7.4。,图 7.5,例7.4 import java.io.*;public class FileCopy public static void main(String args)throws IOException FileInputStream f1;FileOutputStream f2;f1=new FileInputStream(FileCopy.java);f2=new FileOutputStream(acopy_of_java_file);,int temp;while(temp=f1.read()!=-1)f2.write(temp);f1.close();f1.close();public FileCopy()在该例中,我们利用字节流将本程序拷贝至另一个文件acopy_of_java_file中,如果指定的文件不存在,则创建一个新文件,否则原文件的内容会被新写入的内容覆盖。当程序运行后,将生成一个与原程序相同的副本。,2Character流(字符流)文件的读取 该类如图7.2所示,输入/输出类的父类为Reader、Writer,其基本的方法有:Reader int read()int read(char buf)int read(char buf,int offset,int length)close(),Writer int write(int c)int write(char buf)int write(char buf,int offset,int length)close()读者可与字节流进行比较,注意二者方法的区别。下面我们用字符流来改写例7.4:,例7.5 import java.io.*;public class FileCopy public static void main(String args)throws IOException FileReader f1;FileWriter f2;f1=new FileReader(FileCopy.java);f2=new FileWriter(acopy_of_java_file);,int temp;while(temp=f1.read()!=-1)f2.write(temp);f1.close();f2.close();public FileCopy(),例7.6import java.io.*;public class ReadFile public static void main(String args)throws IOException FileReader fr=new FileReader(ReadFile.java);BufferedReader br=new BufferedReader(fr);String line=br.readLine();while(line!=null),System.out.println(line);line=br.readLine();br.close();本程序中,我们通过类BufferedReader对文件实现按行读取,达到一行一行输出的目的,结果如图7.6所示。,图 7.6,3二进制数据流的文件读取 如果要读取与机器无关的基本数据类型的数据,如整型或浮点型的二进制数,就要用到二进制数据文件流DataInputStream、DataOutputStream。实际使用中,类DataInputStream和DataOutputStream必须和一个输入类(InputStream)或输出类(OutputStream)联接起来,不能直接用文件名或文件对象(File)对其直接初始化,例如:,例7.7import java.io.*;public class DatastreamDemo public static void main(String args)throws IOException FileOutputStream f2=new FileOutputStream(data);DataOutputStream dfo=new DataOutputStream(f2);dfo.writeBoolean(true);,dfo.writeInt(100);dfo.writeFloat(200.2f);f2.close();dfo.close();FileInputStream f1=new FileInputStream(data);DataInputStream dfi=new DataInputStream(f1);boolean b=dfi.readBoolean();int i=dfi.readInt();float f=dfi.readFloat();f1.close();dfi.close();System.out.println(The value is:);,(+b);(+i);(+f);public DatastreamDemo(),该例中,我们首先利用类DataOutputStream生成一个二进制文件data,并对它写入三个不同类型的数据:布尔型、整型、浮点型。然后利用DataInputStream读入刚刚输入的数据并显示出来,结果如图7.7所示。可以看出,输出结果与我们的输入是一一对应的。,图 7.7,4随机访问文件的读取 对于InputStream/OutputStream、Reader/Writer类来说,它们都是顺序访问流,只能进行顺序读写。而所谓随机读写,是指读写完上一个字节后,不只能读写其后继的字节,还可以读写文件中任意的字节,就好象文件中有一个随意移动的指针一样。Java语言提供了类RandomAccessFile来进行随机文件的读取。在生成一个RandomAccessFile对象时,不仅要说明文件对象或文件名,同时还需指明访问模式,即“只读方式”(r)或“读写方式”(rw),这类似于C/C+中的fopen()函数。,随机文件处理,使用流的形式对文件进行读写必须顺序进行,也就是说这些文件流的数据必须按先后次序进行处理。在对某些顺序存储访问介质,例如磁带等进行访问时,这样的文件流方式非常有用 随机文件存取提供了一种更灵活的文件读写方式,它允许对文件的内容进行非顺序的访问。在这里,“随机”是指所存取的数据不需要与以前存取过的历史数据有任何的关系。使用随即文件存取方式可以在打开一个文件后同时进行读写操作,并且可以移动文件指针使其指向文件中的任何位置,随机存取文件的结构,在文件内部,文件被分成固定长度的数据块(记录)。从概念上来说,文件可以看作是一个记录数组。文件指针的移动是以记录为单位的。,RandomAccessFile类,RandomAccessFile类的构造函数使用了两个参数,第一个参数表示要操作的文件,可以使用字符串类型的文件名也可以使用一个文件对象;第二个字符串类型的参数mode表示了对文件的操作方式:mode为”r”时表示可以从文件读取;mode 为”rw”时表示既可以从文件读取也可以向文件写入 RandomAccessFile类通过实现DataInput和DataOutPut的方法来实现文件数据的读写,这些方法允许使用二进制编码形式将基本的Java类型写入或读出文件。在RandomAccessFile类中还提供了一些操作文件指针的方法,如通过seek方法可以将文件指针移动到其参数所制定的位置。,RandomAccessFile类的功能类似于DataOutputStream类和DataInputStream类的功能合并,即实现了在一个流中进行读、写两种功能。其常用的方法如表7.2所示。,表7.2 RandomAccessFile类的常用方法,例程,importjava.io.*;publicclassFileTest publicstaticvoidmain(Stringargs)throwsIOException RandomAccessFileraf=newRandomAccessFile(foo.txt,rw);try Writerout=newOutputStreamWriter(newFileOutputStream(raf.getFD(),UTF-8);out.write(HelloWorld!);out.flush();raf.seek(6);out.write(Java);out.flush();finally raf.close();,例7.8的功能与例7.7一样,只不过是用RandomAccessFile来实现的。例7.8import java.io.*;public class RandomDemo public static void main(String args)throws IOException RandomAccessFilefa=new RandomAccessFile(data,rw);,fa.writeBoolean(true);fa.writeInt(100);fa.writeFloat(200.2f);fa.seek(0);boolean b=fa.readBoolean();int i=fa.readInt();float f=fa.readFloat();System.out.println(The value read from a random file is:);(+b);(+i);(+f);,fa.close();public RandomDemo()程序运行结果如图7.8所示。,图 7.8,例程,import java.io.*;class Copy private 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);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(IOException ex)System.err.println(ex);,例程-cont.,public class UseCopypublic static void main(String args)Copy c=new Copy();c.cat(“in.dat”,”out.dat”);,7.3.2 内存的I/O流 表7.3给出了Java支持内存读/写的类,总结起来有以下两类。(1)对应字节内存读/写的有ByteArrayInputStream、ByteArrayOutputStream及String BufferInputStream。它们可以从字节数组中读取数据或向字节数组中写入数据。例如:例7.10 import java.io.*;public class MemoryDemo,public static void main(String args)throws IOException byte b=111,100,74,98,80,69;byte temp=new byte10;ByteArrayInputStream bi=new ByteArrayInputStream(b);ByteArrayOutputStreambo=new ByteArrayOutputStream();StringBufferInputStream bs=new StringBufferInputStream(A demo for memory input!);int x;while(x=bi.read()!=-1),bo.write(x);System.out.println(The result of ByteArrayOutputStream is:+bo);bs.read(temp,0,4);System.out.print(The result of StringBufferOutputStream is:);for(int i=0;i=3;i+)(+tempi);();(+bs);运行结果如图7.9所示。,图 7.9,对于ByteArrayOutputStream来说,我们先从ByteArrayInputStream类中把字节流读入bo的缓冲区中,然后直接进行输出,该对象调用自己的toString()进行输出格式转换。(2)对应字符内存读/写的有CharArrayReader、CharArrayWriter、StringReader及StringWriter。它们可以从字符数组中读取数据或向字符数组中写入数据。例如:例7.11 import java.io.*;public class MemoryDemo,public static void main(String args)throws IOException char b=a,t,e,s,t,d,e,m,o;char temp=new char10;CharArrayReader br=new CharArrayReader(b);CharArrayWriter bw=new CharArrayWriter();StringReader bsr=new StringReader(test demo!);StringWriter bsw=new StringWriter();int x;while(x=br.read()!=-1)bw.write(x);,System.out.println(The result of CharArrayReader is:+bw);bsr.read(temp,0,4);System.out.print(The result of StringReader is:);for(int i=0;i=3;i+)(+tempi);();bsw.write(hello,everybody!);System.out.print(The result of StringWriter is:);(+bsw);程序运行结果如图7.10所示。,图 7.10,我们可以发现以上两个程序的基本架构无大的区别,只是对不同内存流,构造方法有所不同。上述的几种输出内存流,它们在初始化的时候,缺省的缓冲区的大小均为32个字节。当然,实际操作过程中,缓冲区的大小会随数据的写入自动增加。不同的类会有多种不同的方法,方法的使用建立在对各种流的熟悉程度之上,读者应尽可能的学习Java联机文档的内容,获取更多的知识。,内存流,为了支持内存上的输入输出,java.io包内提供了一组相关的类:字节流类ByteArrayInputStream ByteArrayOutputStream StringBufferInputStream字符流类CharArrayReader CharArrayWriter StringReader StringWriter,例程,importjava.io.*;publicclassByteArrayOutputStreamTest publicstaticvoidmain(Stringargs)try ByteArrayOutputStreambaos=newByteArrayOutputStream();PrintStreamps=newPrintStream(baos);for(inti=0;i1000;i+)ps.println(i+ABCDEFGHIJKLMNOPQRSTUVWXYZ);longstart=System.currentTimeMillis();FileOutputStreamfos=newFileOutputStream(ByteArrayOutputStreamTest);baos.writeTo(fos);fos.close();longstop=System.currentTimeMillis();System.out.println(timeelapsed(milliseconds)=+(stop-start);catch(FileNotFoundExceptionfnfe)System.out.println(fnfe.getMessage();catch(IOExceptionioe)System.out.println(ioe.getMessage();,7.3.1 管道流 管道流(PipedStream)可用来把一个程序、线程或代码段的输出直接连接到另一个程序、线程或代码段的输入。Java中管道的类有PipedReader、PipedWriter、PipedInputStream及PipedOutputStream。,管道流,使用过程中,管道输入流作为一个通信管道的接收端,进行数据的读取,管道输出流则作为发送端,进行数据的传送。管道流必须是输入输出并用,也就是说在使用管道前,两者必须进行连接。,为什么要用到管道流?,当某个程序的输出作为另外一个程序的输入时,如果没有管道,就必须为程序提供一个存放中间结果的位置,前一个程序将输出数据写入该位置,而后一个程序再从该位置读出这些数据,这样的做法无疑是低效率的。通过管道,可以连接程序的输出和输入,直接将前一程序的输出作为后一程序的输入,提高了程序效率。,管道流的连接方式,java.io中为字符类型和字节类型各提供了一对输入输出管道流类:PipedReader/PipedWriter和PipedInputStream/PipedOutputStream。管道流的连接方式有两种,以PipedInputStream/PipedOutputStream为例:在构造方法中进行连接:PipedInputStream(PipedOutputStream pos);PipedOutputStream(PipedInputStream pis);通过各自的connect()方法连接:在类PipedInputStream中,connect(PipedOutputStream pos);在类PipedOutputStream中,connect(PipedInputStream pis);,例程,class PipedExample public static void main(String args)throws IOException byte dataA=123,dataB=321;PipedInputStream pis=new PipedInputStream();PipedOutputStream pos=new PipedOutputStream(pis);System.out.println(PipedInputStream);try pos.write(dataA);pos.write(dataB);System.out.println(byte)pis.read();System.out.println(byte)pis.read();finally pis.close();pos.close();,过滤器流,在某些情况下,对于由程序写入或读取的数据,需要在写入或读取之前对其进行处理或者过滤 总的来说,过滤器的作用是对相关输入输出流中的数据进行处理,而对于程序而言,这些过滤器是透明的。,7.3.4 过滤流 过滤流在读/写数据的同时可以对数据进行处理。Java提供了多个具有过滤功能的输入/输出类,字节类过滤流的父类均为FilterInputStream、FilterOutputStream。,过滤器流类,FilterReader/FilterWriter 过滤流是建立在其他流之上的,也就是说,当使用一个过滤流时,必须首先把过滤流连接到某个输入/输出流上。比如,可以通过输入过滤流的方法read()从下层流中读取数据,通过输出过滤流的write()方法把数据写入下层流。,例程,import java.io.*;public class ReadLineTest public static void main(String args)try BufferedReader br=new BufferedReader(new FileReader(args0);String line=null;int i=0;while(line=br.readLine()!=null)i+;System.out.println(i+:+line);br.close();catch(Exception e)e.printS

    注意事项

    本文(java第6章io流.ppt)为本站会员(牧羊曲112)主动上传,三一办公仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对上载内容本身不做任何修改或编辑。 若此文所含内容侵犯了您的版权或隐私,请立即通知三一办公(点击联系客服),我们立即给予删除!

    温馨提示:如果因为网速或其他原因下载失败请重新下载,重复下载不扣分。




    备案号:宁ICP备20000045号-2

    经营许可证:宁B2-20210002

    宁公网安备 64010402000987号

    三一办公
    收起
    展开