ImageVerifierCode 换一换
格式:PPT , 页数:51 ,大小:429.50KB ,
文档编号:3041615      下载积分:28 文币
快捷下载
登录下载
邮箱/手机:
温馨提示:
系统将以此处填写的邮箱或者手机号生成账号和密码,方便再次下载。 如填写123,账号和密码都是123。
支付方式: 支付宝    微信支付   
验证码:   换一换

优惠套餐
 

温馨提示:若手机下载失败,请复制以下地址【https://www.163wenku.com/d-3041615.html】到电脑浏览器->登陆(账号密码均为手机号或邮箱;不要扫码登陆)->重新下载(不再收费)。

已注册用户请登录:
账号:
密码:
验证码:   换一换
  忘记密码?
三方登录: 微信登录  
下载须知

1: 试题类文档的标题没说有答案,则无答案;主观题也可能无答案。PPT的音视频可能无法播放。 请谨慎下单,一旦售出,概不退换。
2: 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。
3: 本文为用户(三亚风情)主动上传,所有收益归该用户。163文库仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对上载内容本身不做任何修改或编辑。 若此文所含内容侵犯了您的版权或隐私,请立即通知163文库(点击联系客服),我们立即给予删除!。
4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
5. 本站仅提供交流平台,并不能对任何下载内容负责。
6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。

版权提示 | 免责声明

1,本文(第8章输入输出流与文件操作课件.ppt)为本站会员(三亚风情)主动上传,163文库仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对上载内容本身不做任何修改或编辑。
2,用户下载本文档,所消耗的文币(积分)将全额增加到上传者的账号。
3, 若此文所含内容侵犯了您的版权或隐私,请立即通知163文库(发送邮件至3464097650@qq.com或直接QQ联系客服),我们立即给予删除!

第8章输入输出流与文件操作课件.ppt

1、第八章第八章 输入输出流与文件操作输入输出流与文件操作 输入输出流的分类 Java流的概念 Java使用流(stream)来执行输入输出(I/O)的功能,流是一 种数据的源头和目的之间的通信途径。 标准输入输出 Java系统事先定义好两个流对象,分别与系统的标准输入 和标准输出相联系,它们是System. in和System.out System是Java中一个功能很强大的类,利用它可以获得很 多Java运行时的系统信息。 3132输出流输出流(程序写出数据程序写出数据) 输入流输入流(程序读入数据程序读入数据) Java中根据流操作的种类可分为:字节流和字符流。根据流的方向,流可分为两类:输

2、入流和输出流。Java流类体系结构流类体系结构1 Java流类体系结构流类体系结构2Java流类体系结构流类体系结构3 Java流类体系结构流类体系结构4 Java流的概念输入输出流的分类【例8.1】标准输入输出举例。 标准输入输出 输入输出流的分类import java.io.*;public class IODemopublic static void main(String args) throws IOException int b; int count=0; while(b=System.in.read()!=-1)count+;System.out.print(char)b); S

3、ystem.out.println(); System.out.println(program end); 运行结果:运行结果:输入:输入:a,b,c,d 输出:输出:a,b,c,d输入:输入:Z 输出:输出: program end目录和文件管理目录和文件管理 32文件名的处理文件名的处理 31FileFile类类 文件或目录的生成文件或目录的生成 文件属性测试文件属性测试 普通文件信息和工具普通文件信息和工具 目录操作目录操作 public File(String path):如果path是实际存在的路径,则该File对象表示的是目录;如果path是文件名,则该File对象表示的是文件。p

4、ublic File(String path,String name):path是路径名,name是文件名(不可为空)。public File(File dir,String name):dir是路径名,name是文件名。String getName( ):得到一个文件的名称(不包括路径)。String getPath( ):得到一个文件的路径名。String getAbsolutePath( ):得到一个文件的绝对路径名。String getParent( ):得到一个文件的上一级目录名。String renameTo(File newName):将当前文件名更名为给定文件的完整路径。【例8

5、.2】 boolean exists( ):测试当前File对象所指示的文件或目录是否存在,若存在,返回True。boolean createNewFile():创建当前文件。boolean canWrite( ):测试当前文件是否可写。boolean canRead( ):测试当前文件是否可读。boolean isFile( ):测试当前文件是否是文件(不是目录)。boolean isDirectory( ):测试当前文件是否是目录,若为目录则返回True。【例8.3】 long lastModified( ):得到文件最近一次修改的时间。long length( ):得到文件的长度,以字节

6、为单位,若不存在,返回0。boolean delete( ):删除File对象代表的文件或目录,目录需为空。删除成功,返回True。boolean mkdir():生成一个由该对象指定的路径(新目录),若成功,返回True。boolean mkdirs():生成一个新的目录,包含子目录。若成功,返回true。boolean renameTo(File newName):将当前File对象所代表的路径名改为newName所代表的路径名。若成功,返回true。String list():列出当前目录下的文件。【例8.4】 FileFile类的应用类的应用 【例8.5】 【例8.6】 字节流字节流

7、缓冲区流缓冲区流BufferedInputStream和BufferedOutputStream 33顺序读/写文件(FileInputStream与FileOutputStream) 31ByteArrayInputStream和ByteArrayOutputStream 32顺序读/写文件(FileInputStream与FileOutputStream) FileInputStream类从磁盘文件读取数据。常用的构造方法有:FileInputStream(String name):打开文件name用来读取数据。如:FileInputStream f =new FileInputStrea

8、m(c:/test.txt);FileInputStream(File file):打开文件file用来读取数据。如:File f=new File(c:/test.txt); FileInputStream f1=new FileinputStream(f);FileOutputStream类创建文件(如果文件不存在),并将数据写入文件。FileOutputStream类常用的构造方法有:FileOutputStream(String name):打开文件name用来写入数据。如:FileOutputStream f=new FileOutputStream (c:/test.txt);Fi

9、leOutputStream(File file):打开文件file用来写入数据。如:File f =new File(c:/test.txt);FileOutputStream f1=new FileOutputStream (f);FileOutputStream(String name,Boolean append):打开文件name用来写入数据,若append为true,则写入的数据会加到原有文件后面,否则,覆盖原有的文件。如:FileOutputStream f =new FileOutputStream(c:/test.txt,true);字节流字节流 字节流字节流【例8.7】将F

10、ileIO.java复制为FileExam.java.bak。 import java.io.*;public class FileIOpublic static void main(String args) FileInputStream inFile=null; FileOutputStream outFile=null; tryinFile=new FileInputStream(FileIO.java); outFile=new FileOutputStream(FileExam.java.bak); int data; while(data=inFile.read()!=-1)out

11、File.write(data); catch(FileNotFoundException e)System.out.println(e.getMessage(); catch(IOException e)System.out.println(e.getMessage(); finallyif(inFile!=null)tryinFile.close();catch(IOException e) if(outFile!=null)tryoutFile.close();catch(IOException e) 程序运行结果程序运行结果【解题分析】以下问题的求解过程可分解如下:【解题分析】以下问题

12、的求解过程可分解如下:先打开文件先打开文件FileExam.java用用read()将其内容逐字节读取出来将其内容逐字节读取出来(如果返回值为如果返回值为-1,则,则表明已到达文件尾端表明已到达文件尾端)再用再用write()将读出的字节逐一写入另一个文件将读出的字节逐一写入另一个文件FileExam.java.bak中中若文件无法打开若文件无法打开(例如例如FileExam.java不存在不存在)或无法生成或无法生成(FileExam.java.bak),则抛出,则抛出FileNotFoundException异常,异常,若读写出错,则抛出若读写出错,则抛出IOException异常。异常。

13、最后,在最后,在finally中关闭文件。中关闭文件。 在使用在使用FileInputStream类时,若关联的目录或者文件不存在,类时,若关联的目录或者文件不存在,Java会抛出一个会抛出一个IOException异常。程序可以使用异常。程序可以使用try-catch块检测和块检测和处理捕捉到的异常。处理捕捉到的异常。 为了把一个文件输入流对象与一个文件关联起来,可以使用下列为了把一个文件输入流对象与一个文件关联起来,可以使用下列的代码段来处理的代码段来处理Java产生的产生的IOEception异常。异常。 例如:例如:try FileInputStream fis=new FileInp

14、utStream(java.txt); catch(IOException e) System.out.println(File Exception:+e); 注:注:字节流字节流 ByteArrayInputStream和ByteArrayOutputStream 字节流字节流 ByteArrayInputStream 将字节数组用作源,并在该数组中执行读 操作。它有两种构造方法。第一种构造方法将字节数组作为参数。ByteArrayInputStream(byte buffer):生成一个字节数组的输入流,并指定一个字节数组buffer为此输入流的流缓冲区。如:ByteArrayInputS

15、tream b =new ByteArrayInputStream(buf);另外一种构造方法是从指定的字节数组来创建。ByteArrayinputStream b =new ByteArrayinputStream(buf,off,len);其中off是要读取的第一个字节的偏移,len是要读取数组的字节数;ByteArrayOutputStream有2种构造方法。ByteArrayOutputStream():生成一个字节数组的输出流,其缓冲区的默认初始大小为32字节,若有需要,缓冲区的大小会随之增加。如:ByteArrayOutPutStream b=new ByteArrayOutput

16、Stream();ByteArrayOutputStream(int size):创建32个字节的缓冲器用于储存数据,但分配size字节的初始大小给此缓冲区。如:ByteArrayOutputStream b1=new ByteArrayOutputStream(size);创建大小为size的缓冲器ByteArrayOutputStream的一些常用方法:int size():返回此流缓冲区的大小。byte toByteArray():生成一个新的字节数组,并将流的内容复制到此字节数组。String toString():将流的内容转换为String对象。【例8.8】程序读入文件ByteIO

17、.java,将其内容写入内存中(一个字节数组),接着转换为String对象。 字节流字节流import java.io.*;import java.util.*;public class ByteIOpublic static void main(String args) tryFile inFile=new File(“ByteIO.java); FileInputStream inData=new FileInputStream(inFile); ByteArrayOutputStream dataArray=new ByteArrayOutputStream(); int data; w

18、hile(data=inData.read()!=-1)dataArray.write(data); inData.close(); String dataStr=dataArray.toString(); catch(IOException e)System.out.println(e.getMessage(); 字节流字节流 缓冲区流缓冲区流BufferedInputStream和BufferedOutputStream BufferedInputStream类的构造方法和方法:BufferedInputStream(InputStream in):构造一个BufferedInputStr

19、eam。BufferedInputStream(InputStream in, int size):构造一个具有给定的缓冲区大小的BufferedInputStream。int available():得到可以从这个输入流读取的字节数。void close():关闭流。int read():读取数据的字节。int read(byte b, int off, int len):从这个字节输入流的给定偏移量处开始读取字节,存储到给定的字节数组。void reset():将缓冲区重新设置到加标记的位置。long skip(long n):跳过n个字节的数据。BufferedOutputStream类

20、的构造方法和方法:BufferedOutputStream(OutputStream out):构造一个BufferedOutputStream。BufferedOutputStream(OutputStream out, int size):构造一个具有给定的缓冲区大小的BufferedOutputStream。void flush():刷新这个流。void write(byte b, int off, int len):将给定的字节数组写到这个缓冲输出流。void write(int b):将给定的字节写到这个缓冲输出流。 【例8.9】文件拷贝的缓冲改进。 字节流字节流import jav

21、a.io.*;public class Copy public static void main(String args) BufferedInputStream bis=null; BufferedOutputStream bos=null; byte buf=new byte100; try bis=new BufferedInputStream(new FileInputStream(test.txt); bos=new BufferedOutputStream(new FileOutputStream(testcopy.txt); int len=0; while( true ) le

22、n=bis.read(buf); if(len=0) break; bos.write(buf,0,len); bos.flush();/缓冲区只有满时才会将数据输出到输出流,用缓冲区只有满时才会将数据输出到输出流,用flush()将未满的缓冲区中数将未满的缓冲区中数据强制输出据强制输出 catch(Exception e)e.printStackTrace(); finally if(bis != null) try bis.close(); catch(Exception e) e.printStackTrace(); if(bos!= null) try bos.close(); cat

23、ch(Exception e) e.printStackTrace(); 程序运行结果字符流字符流 31ReaderReader和和Writer Writer 32InputStreamReaderInputStreamReader和和OutputStreamWriterOutputStreamWriter 33FileReaderFileReader和和FileWriterFileWriter 34 35BufferedReaderBufferedReader和和BufferedWriterBufferedWriter CharArrayReaderCharArrayReader和和Char

24、ArrayWriterCharArrayWriterWriter和和Reader 以字符流方式向文件写入或从文件中读取数据,可以使用以字符流方式向文件写入或从文件中读取数据,可以使用Writer和和Reader类及其子类。类及其子类。 Writer和和Reader类都是抽象类,不能建立它们的对象,所以只能通过类都是抽象类,不能建立它们的对象,所以只能通过它们子类对象对文件进行操作。常用的它们子类对象对文件进行操作。常用的Writer类的子类包括类的子类包括FileWriter类类和和BufferedWriter类。类。FileWriter类构造方法如下:类构造方法如下:FileWriter(S

25、tring fileName):参数:参数fileName表示带路径的磁盘文件名。表示带路径的磁盘文件名。FileWriter(File file):参数:参数file表示为磁盘文件所建立的表示为磁盘文件所建立的File对象名。对象名。 注:使用注:使用FileWriter进行文件操作时,为了减少磁盘读写次数,常常进行文件操作时,为了减少磁盘读写次数,常常使用具有缓冲功能的使用具有缓冲功能的BufferedWriter类。类。 字符流字符流InputStreamReader和OutputStreamWriter InputStreamReader类的构造方法和方法:InputStreamRea

26、der(InputStream in):构造一个InputStreamReader。InputStreamReader(InputStream in, String enc):使用命名的字符编码构造一个InputStreamReader。void close():关闭流。String getEncoding():得到字符编码的名称。int read():读取一个字符。int read(char cbuf, int off, int len):将字符读到数组中。boolean ready():如果这个流已准备好,返回True。OutputStreamWriter类的构造方法和方法:OutputS

27、treamWriter(OutputStream out):构造一个OutputStreamWriter。OutputStreamWriter(OutputStream out, String enc):使用命名的字符编码构造一个OutputStreamWriter。void close():关闭流。void flush():刷新流。String getEncoding():得到这个流使用的字符编码的名称。void write(char cbuf, int off, int len):写字符数组的一部分。void write(int c):写一个字符。void write(String str

28、, int off, int len):写一个字符串的一部分。【例8.10】利用InputStreamReader从键盘接受输入,再将输入的字符显示出来。 字符流字符流 import java.io.*;class inputstreamreader public static void main(String args) try int character; InputStreamReader instreamread = new InputStreamReader(System.in); /InputStreamReader以字符形式读取输入以字符形式读取输入 while (charact

29、er = instreamread.read() != -1) System.out.print(char) character); catch (IOException e) System.out.print(“Bye”);运行结果:运行结果:输入:输入:a,b,c,d 输出:输出:a,b,c,d输入:输入:1,2,3,4 输出:输出:1,2,3,4输入:输入:Z 输出:输出:Bye字符流字符流FileReader FileReader(File file):构造一个FileReader。FileReader(FileDescriptor fd):从一个文件描述符构造一个FileReader

30、。FileReader(String filename):从一个文件名构造一个FileReader。【例8.11】下例中打开一个文件file.txt(内容为:Hello from file),将文件的内容 读到缓冲区,然后显示数据 。字符流字符流 import java.io.*;public class filereadpublic static void main(String args) throws ExceptionFileReader fileread = new FileReader(file.txt);/打开文件打开文件char data = new char1024;int

31、charsread = fileread.read(data);/读入读入System.out.println(new String(data,0,charsread);/显示显示fileread.close();/关闭文件流关闭文件流程序运程序运行结果行结果 字符流字符流FileWriter FileWriter(File file):从File对象构造一个FileWriter。FileWriter(FileDescriptor fd):从文件描述符构造一个FileWriter。FileWriter(String filename):从文件名构造一个FileWriter。FileWriter

32、(String filename, boolean append):构造一个可附加的FileWriter。字符流字符流【例8.12】下例中,分别采用三种方式:逐字符地写数据、一次写入所有数据、分批写数据,使用类FileWriter。import java.io.*;public class filewritepublic static void main(String args) throws Exception char data=T,h,i,s, ,i,s, ,a, ,s,t,r,i,n,g, ,o,f, ,t,e,x,t,.; FileWriter filewriter1=new Fil

33、eWriter(file1.txt); for(int loop_index=0;loop_indexdata.length;loop_index+)filewriter1.write(dataloop_index); FileWriter filewriter2=new FileWriter(file2.txt); filewriter2.write(data); FileWriter filewriter3=new FileWriter(file3.txt); filewriter3.write(data,5,10); filewriter1.close(); filewriter2.cl

34、ose(); filewriter3.close(); 运行结果:运行结果:file1.txt和和file2.txt的内容为:的内容为:This is a string of textfile3.txt的内容为:的内容为:is a strin字符流字符流BufferedReader和BufferedWriter 这两个类对应的流使用了缓冲,能大大提高输入输出的效率。这两个也是过滤器流,常用来对InputStreamReader和OutputStreamWriter进行处理。字符流字符流【例8.13】从键盘接受输入并回显。 import java.io.*;public class Echote

35、st public static void main(String args) BufferedReader in =new BufferedReader(new InputStreamReader(System.in); String s; System.out.print(please enter a string:); try while(s = in.readLine().length() != 0) System.out.println(输入是:输入是:+s); catch(IOException e) e.printStackTrace(); 程序运行结果程序运行结果 字符流字符流

36、CharArrayReader和CharArrayWriter CharArrayReader类的构造方法和方法如下:CharArrayReader(char buf):从给定的字符数组构造一个CharArrayReader。CharArrayReader(char buf, int offset, int length):同上。void close():关闭流。void mark(int readAheadLimit):在流中的当前位置加标记。boolean markSupported():如果这个流支持mark操作,那么返回True。int read():读取一个字符。int read(c

37、har b, int off, int len):将读入数组的一部分。boolean ready():检查这个流是否已经准备好被读取。void reset():将流重设到最近的标记。long skip(long n):跳过n个字符。(2)CharAraayWriter类的构造方法和方法同上类似。字符流字符流【例8.14】下例演示CharArrayReader类的作用,该例从字符数组中逐个读取字符并显示。chararrayreader.javaimport java.io.*;public class chararrayreader public static void main(String

38、args) throws IOException char data = T,h,i,s, ,i,s, ,a, ,s, t,r,i,n,g, ,o,f, ,t,e,x,t,.; CharArrayReader chararrayreader = new CharArrayReader(data); int character; while(character = chararrayreader.read() != -1) System.out.print(char)character); 运行结果:运行结果:This is a string of text.文件的随机访问文件的随机访问 31在

39、java中,类RandomAccessFile 提供了随机访问文件的方法RandomAccessFile(File file, String mode):构造一个随机访问文件流,file为被访问的文件对象,mode是用来指定存取的模式,mode可以为r(读)、w(写)或rw(读写)。RandomAccessFile(String name,String mode):构造一个随机访问文件流,以便访问由字符串name指定名字的文件,mode参数使用同上 32RandomAccessFile类提供用来读取某种基本数据类型的数据或字符串的方法 boolean readBoolean()byte rea

40、dByte()char readChar()double readDouble()float readFloat()int readInt()long readLong()short readShort()String readLine() 33RandomAccessFile类提供用来向文件中写入某种基本类型的数据或字符串的方法 void writeByte(byte b)void writeBytes(String s)void writeChar(char c)void writeChars(String s)void writeDouble(double d)void writeFlo

41、at(float f)void writeInt(int i)void writeLong(long l)void writeShort(short s)34和目前文件位置有关的方法 void seek(long pos):将文件指针移到pos(不可为负)的位置,相对于文件初始位置值(初始值为0)。long getFilePointer():得到目前文件指针的位置(相对于文件初始位置)。long length():得到文件的长度。int skipBytes( int n ):使文件指针向前移动指定的n个字节文件的随机访问文件的随机访问【例8.15】把若干个32位整数写到一个名为test.txt

42、的文件中,利用 seek()方法,以相反的顺序读取这些数据。 import java.io.*;public class RandomFile public static void main(String args) RandomAccessFile raf=null; int data=12,31,56,23,27,1,43,65,4,99; try raf=new RandomAccessFile(test.txt,rw); for(int i=0;i=0;i-) raf.seek(i*4);System.out.println(raf.readInt(); catch(Exception

43、 e)e.getMessage(); finally if(raf!=null) tryraf.close();catch(Exception e)e.getMessage(); 程序运行结果程序运行结果 使用使用DataOutputStream类向文件中写入各种类型数据的操作步骤:类向文件中写入各种类型数据的操作步骤:1 1、为磁盘文件建立、为磁盘文件建立File类对象;类对象;2 2、为该、为该File对象建立对象建立FileOutputStream类流对象,建立其与磁盘文件的类流对象,建立其与磁盘文件的连接;连接;3 3、为该、为该FileOutputStream类对象建立类对象建立Da

44、taOutputStream类对象,利用类对象,利用DataOutputStream类的类的writeInt(),writeFloat(),writeDouble(),writeBoolean()等方法分别向文件中写入整型、单精度型、双精度等方法分别向文件中写入整型、单精度型、双精度型、布尔型等数据;型、布尔型等数据; 4 4、写入操作完成后,利用、写入操作完成后,利用close()close()方法将流关闭,断开与磁盘文件的方法将流关闭,断开与磁盘文件的联系。联系。 DataOutputStream流类流类import java.io.*;public class File public s

45、tatic void main(String args) throws IOException int ch;File file1=new File(c:jdk1.3exampledataFile.txt);File file2=new File(c:jdk1.3exampleoutFile.txt);try FileInputStream fin= new FileInputStream(file1);DataInputStream din =new DataInputStream(fin);int i=din.readInt();float f=din.readFloat();boolea

46、n b=din.readBoolean(); din.close();从磁盘文件读取各类数据 【例8.16】FileOutputStream fout= new FileOutputStream(file2);DataOutputStream dout =new DataOutputStream(fout);dout.writeInt(i); dout.writeFloat(f);dout.writeBoolean(b);dout.close();System.out.println(整数:+i);System.out.println(浮点数:+f);System.out.println(布尔

47、量:+b);catch (FileNotFoundException e) System.out.println(e);catch (IOException e) System.out.println(e); 从磁盘文件读取各类数据 import java.io.*;public class File public static void main(String args) int ch; InputStreamReader iin=new InputStreamReader(System.in); BufferedReader bin =new BufferedReader(iin); Fi

48、le file1=new File(c:jdk1.3exampledataFile.txt); try FileOutputStream fout= new FileOutputStream(file1); DataOutputStream dout =new DataOutputStream(fout); System.out.println( 输入整数输入整数); int i=Integer.parseInt(bin.readLine(); System.out.println( 输入浮点数输入浮点数); 向磁盘文件写入各类数据【例8.17】 float f=Float.parseFloa

49、t(bin.readLine(); System.out.println( 输入布尔量输入布尔量); boolean b=new Boolean(bin.readLine().booleanValue(); dout.writeInt(i); dout.writeFloat(f); dout.writeBoolean(b); dout.close(); catch (FileNotFoundException e) System.out.println(e);catch (IOException e) System.out.println(e); 向磁盘文件写入各类数据import java.

50、io.*;public class File public static void main(String args) throws IOExceptionint ch;File file1=new File(c:jdk1.3examplenewFile.txt);tryFileInputStream fin= new FileInputStream(file1);System.out.println(文件中的信息为:);ch= fin.read();while (ch !=-1) System.out.print(char)ch); ch =fin.read(); fin.close();

侵权处理QQ:3464097650--上传资料QQ:3464097650

【声明】本站为“文档C2C交易模式”,即用户上传的文档直接卖给(下载)用户,本站只是网络空间服务平台,本站所有原创文档下载所得归上传人所有,如您发现上传作品侵犯了您的版权,请立刻联系我们并提供证据,我们将在3个工作日内予以改正。


163文库-Www.163Wenku.Com |网站地图|