《文件和数据流》PPT课件_第1页
《文件和数据流》PPT课件_第2页
《文件和数据流》PPT课件_第3页
《文件和数据流》PPT课件_第4页
《文件和数据流》PPT课件_第5页
已阅读5页,还剩77页未读 继续免费阅读

下载本文档

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

文档简介

1、第七章 文件和数据流,浙江工业大学 计算机学院 赵小敏 59:9001,主要内容,流的基本概念 字节流 字符流 文件类 随机读写文件 对象序列化,7.1流的基本概念,数据流是从源到目的的字节的有序序列,先进先出。 两种基本流:InputStream(输入流)和OutputStream(输出流),Java的标准输入输出,标准输入输出是指在命令行方式下的输入输出方式。 Java通过System.in、System.out和System.err来实现标准输入输出和标准错误输出。 每当main方法被执行时,就自动生成System.in、System.out和Syst

2、em.err三个对象。,Java的标准输入输出,System.in是字节输入流InputStream类的一个对象,其中有read方法从键盘读入数据: public int read() throws IOException public int read(byte b) throws IOException System.out是流PrintStream类的一个对象,其中print和println方法向屏幕输出数据。 System.err是流PrintStream类的一个对象,用于向屏幕输出错误信息。,例1:输入输出的实例,public class Stdin_out public stati

3、c void main(String args) byte buffer =new byte200; int i,d=0,count=0; System.out.print(Input a string: ); try count=System.in.read(buffer); catch(Exception e) System.err.println(发生异常:+ e.toString(); for(i=0;i=count-1;i+) System.out.print(char)bufferi); System.out.println(count); System.out.println(I

4、nput ten char: ); for(i=1;i=10;i+) try d=System.in.read(); System.out.println(char)d); catch(Exception e) System.err.println(发生异常:+e.toString(); ,Java的数据流,Java的数据流都在java.io包里 Java的数据流根据操作的数据流分为字节流和字符流 字节流:流中的数据以8位字节为单位进行读写,以InputStream和OutputStream为基础类。 字符流:流中的数据以16位字节为单位进行读写,以Reader和Writer为基础类。,7.2

5、字节流,InputStream和OutputStream分别是字节输入流和字节输出流的超类 InputStream和OutputStream提供许多用于字节输入输出的方法,包括: 数据的读取 数据的写入 标记位置 获取数据量 关闭数据流,字节输入流InputStream类的层次结构,InputStream 方法,三个基本read()方法 int read()/读一个字节返回 int read(byte ) / 将数据读入byte, 返回读的字节数 int read( byte, int offset, int length ) 其它方法 void close( ) /关闭流。自顶向下关闭Fil

6、ter stream int available() /返回未读的字节数 long skip(long n) / 跳过n个字节 boolean markSupported( ) /测试打开的流是否支持书签 void mark(int) /标记当前流,并建立int大小缓冲区 void reset( ) / 返回标签出,字节输出流OutputStream类层次,OutputStream方法,三个基本的write( )方法 void write( int ) / 写一个字节 void write(byte ) / 写一个字节数组 void write(byte , int offset, int l

7、ength ) 其它方法 void close( ) void flush( ) / 强行写,字节文件输入输出流:FileInputStream和FileOutputStream,FileInputStream和FileOutputStream实现了对文件的顺序访问,以字节为单位对文件进行读写操作,主要有这样几步: 创建文件输入输出流的对象 用文件读写方法读写数据 关闭数据流。,1、创建文件输入输出流对象,(1)创建FileInputStream的对象,打开要读取数据的文件 FileInputStream的构造方法是: public FileInputStream(String name) t

8、hrows FileNotFoundException public FileInputStream(File file) throws FileNotFoundException 如下面语句可以创建文件的输入流对象,并打开要读取数据的文件D:/java/temp/mytext.txt : FileInputStream rf=new FileInputStream(“D:/java/temp/mytext.txt ”);,1、创建文件输入输出流对象,(2)创建FileOutputStream的对象,打开要写入数据的文件 FileOutputStream的构造方法是: public FileO

9、utputStream(String name) throws FileNotFoundException public FileOutputStream(String name,boolean append) throws FileNotFoundException public FileOutputStream(File file) throws FileNotFoundException 其中:name是要打开的文件名,file是文件类File的对象。如下面语句可以创建文件的输出流对象,并打开要写入数据的文件D:/java/temp/mytext.txt : FileOutputStre

10、am wf=new FileOutputStream(“D:/java/temp/mytext.txt ”);,2、对文件进行读写的方法,(1)用read方法读取文件的数据 public int read( ) throws IOException /返回从文件中读取的一个字节。 public int read(byte b) throws IOException public int read(byte b,int off,int len) throws IOException /返回读取的字节数,若b的长度为0,返回0。,2、对文件进行读写的方法,(2)用write方法将数据写入文件 pu

11、blic void write(int b) throws IOException /向文件写入一个字节,b是int类型,所以将b的低8位写入 public void write(byte b) throws IOException public void write(byte b,int off,int len) throws IOException /将字节数组写入文件,其中off是b中的起始位置,len是写入的最大长度。,3、字节文件流的关闭,当读写操作完毕时,要关闭输入或输出流,释放相关的系统资源。 如果发生I/O错误,抛出IOException异常。 关闭数据流的方法是: publi

12、c void close( ) throws IOException,例2:读取文件内容并显示在屏幕,import java.io.*; public class FileIn public static void main(String args) try FileInputStream rf=new FileInputStream( H:/java/temp/mytext.txt); int b; while(b=rf.read()!=-1) System.out.print(char)b); rf.close(); catch(IOException ie) System.out.pri

13、ntln(ie); catch(Exception e) System.out.println(e); ,例3:复制文件,import java.io.*; public class FileIn_Out public static void main(String args) try FileInputStream rf=new FileInputStream(D:/java/temp/file1.txt); FileOutputStream wf=new FileOutputStream(D:/java/temp/file2.txt); byte b=new byte512; int co

14、unt=-1; while(count=rf.read(b,0,512)!=-1) wf.write(b,0,count); rf.close(); wf.close(); catch(IOException ie) System.out.println(ie.toString(); catch(Exception e) System.out.println(e.toString(); ,7.3字符流,类Reader是字符输入流的抽象超类,其提供的方法与InputStream类似,只是将基于Byte的参数改为基于Char。 类Writer是字符输出流的抽象超类,其提供的方法与OutputStr

15、eam类似,只是将基于Byte的参数改为基于Char。 Reader和Writer 类实现字节和字符间的自动转换。 每一个核心输入、输出流,都有相应的Reader和Writer版本。,Reader的类层次结构,Reader的基本方法,int read();/读单个字符 int read(char cbuf);/读字符放入数组中 int read(char cbuf, int offset, int length);/读字符放入数组的指定位置 void close( ) /关闭流。 long skip(long n) / 跳过n个字符 boolean markSupported( ) /测试打开

16、的流是否支持书签 void mark(int) /标记当前流,并建立int大小缓冲区 void reset( ) / 返回标签出 boolean ready() /测试当前流是否准备好进行读,Writer的类层次结构,Writer的基本方法,int write(int c) ; / 写单个字符 int write(char cbuf) ;/ 写字符数组 int write(char cbuf, int offset, int length) ; int write(String str) ; int write(String str, int offset, int length) ; voi

17、d close( ) void flush( ) / 强行写,字符文件输入输出流:FileReader和FileWrite,FileReader和Filewriter类用于字符文件的输入和输出 读写文件的过程: 先创建对象打开文件 然后用读写方法从文件中读取数据或将数据写入文件 最后关闭数据流。,1、创建字符流文件对象,打开文件,创建FileReader或Filewriter对象,打开要读写的文件 FileReader的构造方法: public FileReader(String filename) public FileReader(File file) FileWriter的构造方法: p

18、ublic FlieWriter(String filename) public Filewriter(File file),2、字符文件流的读写,用从超类继承的read和write方法可以对打开的文件进行读写 读取文件数据的方法: int read( ) throws IOException int read(char b ) throws IOException int read(char b ,int off,int len) throws IOException 数据写入到文件的方法: void write(char b) throws IOException void write(c

19、har b ) throws IOException void write(char b ,int off,int len) throws IOException,3、字符文件流的关闭,对文件操作完毕要用close方法关闭数据流。 public void close( ) throws IOException,例5:从键盘输入一行文字,写入文件file3.txt中,import java.io.*; public class FilecharOut public static void main(String args) char c=new char512; byte b=new byte5

20、12; int n,i; try FileWriter wf=new FileWriter(file3.txt); n=System.in.read(b); for(i=0;in;i+) ci=(char)bi; wf.write(c); wf.close(); catch(IOException e) System.out.println(e); ,字符缓冲流: BufferedReader和BufferedWriter,BufferedReader和BufferedWriter类以缓冲区方式对数据进行输入输出。 1.BufferedReader用于字符缓冲输入,构造方法如下: public

21、 BufferedReader(Reader in) public BufferedReader(Reader in,int sz) 其中:in为超类Reader的对象,sz为用户设定的缓冲区大小。,2. BufferedWriter类,Bufferedwriter用于字符缓冲流输出,构造方法为: public BufferedWriter(Writer out) public Bufferedwriter(Writer out,int sz) 其中:out为超类Writer的对象,sz为用户设定的缓冲区大小。,例6:从键盘输入文字存入文件,再读出加上行号后打印在屏幕,import java.

22、io.*; public class BufferDemo public static void main(String args) String f=f.txt; String str=; int i=0; try BufferedReader keyIn=new BufferedReader(new InputStreamReader(System.in); BufferedWriter bw=new BufferedWriter(new FileWriter(f); BufferedReader br = new BufferedReader(new FileReader(f); Sys

23、tem.out.println(Please input file text:); while(!(str=keyIn.readLine().equals(exit) bw.write(str,0,str.length(); bw.newLine(); bw.close(); while(str=br.readLine()!=null) i+; System.out.println(i+: +str); catch(IOException e) ,字节流与字符流的比较,Reader 和 InputStream以及Writer 与 OutputStream定义的API类似,但操作的数据类型不同。

24、 所有的流InputStream、 OutputStream 、Reader、 Writer 在创建时自动打开;程序中可以调用close方法关闭流,否则Java运行环境的垃圾收集器将隐含将流关闭。,7.4文件类,创建文件流:常用文件名或File类的对象创建文件流。 文件过滤:将符合条件的文件选择出来进行操作,通过接口FileFilter和FilenameFilter来实现。,文件类File,提供对文件进行创建目录、创建临时文件、改变文件名、删除文件等操作 提供获取文件信息的方法,如文件名、文件路径和文件长度等 File类的构造方法: public File(String pathname) p

25、ublic File(String parent,String child) public File(File parent,String child) public File(URI uri),File类的方法,1 、访问文件对象 public String getName( ) public String getPath( ) public String getAbsolutePath( ) public String getParent( ) public File getParentFile( ) 2、文件操作 public boolean renameTo(File dest) pu

26、blic boolean delete(),File类的方法(续),3、获得文件的属性 public long length() public boolean exists() public long lastMoidfied() 4、目录操作 public boolean mkdir() public String list() public File listFiles();,例8:文件类的使用,import java.io.*; import java.util.*; public class File_ex void FileInformation(File f) System.out

27、.println(f.getName(); System.out.println(f.getAbsolutePath(); System.out.println(f.getParent(); System.out.println(f.length(); System.out.println(new Date(f.lastModified(); void DirectoryInformation(File d) System.out.println(d.getName(); System.out.println(d.getParent(); int i=0; String lt=d.list()

28、; while(ilt.length) System.out.println(lti); i+; ,例8:文件类的使用(续),public static void main(String args) File f=new File(D:/java/2007-2Java/code/ch08,file1.txt); File d=new File(D:/java/2007-2Java/code/ch08/data2); File d1=new File(D:/java/2007-2Java/code/ch08/data2/data3); File_ex fe=new File_ex(); fe.F

29、ileInformation(f); fe.DirectoryInformation(d); d1.mkdir(); ,练习1:阅读下面的程序,写出带划线语句或注释,并写出该程序的作用。,import java.io.*; public class Test public static void main(String args) scanFiles(c:/); public static void scanFiles(String path) if (path = null) return; File f = new File(path); /_ if (!f.exists() return

30、; if (f.isFile() /_ System.out.println(f.getAbsolutePath(); else File dir = f.listFiles(); for (int i = 0; i dir.length; i+) scanFiles(diri.getAbsolutePath();/_ ,练习2:打印某目录下(包含子目录)所有文件的规范路径名和文件大小,import java.io.*; public class File_Size public static void main(String args)throws IOException File file

31、s=new File(.); listPath(files); public static void listPath(File f)throws IOException String file_list=f.list(); for(int i=0;ifile_list.length;i+) File current_file=new File(f.getPath(),file_listi); if(current_file.isDirectory() listPath(current_file); if(current_file.isFile() try System.out.println

32、(current_file.getCanonicalPath()+:+current_file.length(); catch(IOException e) e.printStackTrace(); /if /for ,文件过滤接口FileFilter和FilenameFilter,这两个接口中有方法accept,接口的说明如下: public interface FileFilter public boolean accept(File pathname); /参数pathname是要过滤目录中的文件对象。 public interface FilenameFilter public boo

33、lean accept(File dir, String name); /参数dir是要过滤的目录,name是目录中的文件名,过滤功能的使用,要实现过滤的功能,就要声明一个类实现FileFilter和FilenameFilter接口中的方法。 在使用File类的list和listFiles方法时,以一个过滤器对象作为参数,就可实现对文件名的过滤。 public String list(FilenameFilter filter) public File listFiles(FilenameFilter filter) public File listFlies(FileFilter filte

34、r),例9:显示C:windows目录下.exe文件。,import java.io.*; class ListFilter implements FilenameFilter private String pre=,ext=; public ListFilter(String filterstr) int i,j; filterstr=filterstr.toLowerCase(); i=filterstr.indexOf(*); j=filterstr.indexOf(.); if(i0) pre=filterstr.substring(0,i); if(i=-1 ,例9:显示C:wind

35、ows目录下.exe文件。,public boolean accept(File dir,String filename) boolean y=true; try filename=filename.toLowerCase(); y=filename.startsWith(pre) ,7.5 文件的随机读写,在文件的任意位置读或写数据,而且可以同时进行读和写的操作。 RandomAccessFile类提供的对文件随机访问方式。 RandomAccessFile的构造方法 public RandomAccessFile(File file,String mode) throws FileNotf

36、oundException public RandomAccessFile(String name,String mode) throws FileNotfoundException file和name是文件对象和文件名字符串。 mode是对访问方式的设定:r表示读,w表示写,rw表示读写,RandomAccessFile的方法,public long length( ) 返回文件的长度 public void seek(long pos) 改变文件指针的位置 public final int readInt( )读一个整型数据 public final void writeInt(int v

37、) 写入一个整型数据 public long getFilePointer( ) 返回文件指针的位置 public void close( ) 关闭文件,例10:随机访问文件的演示程序,import java.io.IOException; import java.io.RandomAccessFile; public class RandomAccessFileDemo public static void main(String args ) try RandomAccessFile f=new RandomAccessFile(test.txt, rw); int i; double d

38、; for (i=0; i10; i+) f.writeDouble(Math.PI*i); f.seek(16); f.writeDouble(0); f.seek(0); for (i=0; i 10; i+) d=f.readDouble( ); System.out.println( + i + : + d); f.close( ); catch (IOException e) System.err.println(发生异常: + e); e.printStackTrace( ); ,7.6 对象序列化,序列化的过程就是对象写入字节流和从字节流中读取对象。将对象状态转换成字节流之后,可

39、以用java.io包中的各种字节流类将其保存到文件中,管道到另一线程中或通过网络连接将对象数据发送到另一主机。 对象序列化的典型应用 在RMI、Socket、JMS、EJB都有应用 程序版本升级问题,序列化机制,序列化分为两部分:序列化和反序列化。 序列化是将数据分解成字节流,以便存储在文件中或在网络上传输。 反序列化是打开字节流并重构对象。 对象序列化不仅要将基本数据类型转换成字节表示,有时还要恢复数据。恢复数据要求有恢复数据的对象实例。,定制对象序列化,实现java.io.Serializable接口的类对象可以转换成字节流或从字节流恢复。 public class Serializabl

40、eClass implements Serializable String today=Today:; transient Date todayDate=new Date(); 只有对象的数据被保存,方法与构造函数不被序列化。 声明为transient或static的变量不能被序列化。,处理对象流(序列化过程和反序列化过程),java.io.ObjectOutputStream负责将对象写入字节流 java.io.ObjectInputStream从字节流重构对象。,序列化过程:序列化todaysdate到一个文件中,FileOutputStream f = new FileOutputStr

41、eam(tmp); ObjectOutputStream s = new ObjectOutputStream(f); s.writeObject(Today); s.writeObject(new Date(); s.flush();,反序列化过程:从文件中反序列化String对象和Date对象,FileInputStream in = new FileInputStream(tmp); ObjectInputStream s = new ObjectInputStream(in); String today = (String)s.readObject(); Date date = (Da

42、te)s.readObject();,例:将Student对象序列化,import java.io.Serializable; public class Student implements Serializable static final long serialVersionUID = 123456L; String m_name; int m_id; int m_height; /int m_weight; public Student( String name, int id, int h ) m_name = name; m_id = id; m_height = h; public

43、 void output( ) System.out.println(姓名: + m_name); System.out.println(学号: + m_id); System.out.println(身高: + m_height); ,例:将Student对象数据写入object.dat,import java.io.FileOutputStream; import java.io.ObjectOutputStream; public class WriteObject public static void main(String args ) try ObjectOutputStream

44、f = new ObjectOutputStream( new FileOutputStream(object.dat); Student s = new Student( 张三, 2003001, 172); f.writeObject(s); s.output( ); f.close( ); catch (Exception e) System.err.println(发生异常: + e); e.printStackTrace( ); ,例:从object.dat读出Student对象数据,import java.io.FileInputStream; import java.io.Obj

45、ectInputStream; public class ReadObject public static void main(String args ) try ObjectInputStream f = new ObjectInputStream( new FileInputStream(object.dat); Student s = (Student)(f.readObject( ); s.output( ); f.close( ); catch (Exception e) System.err.println(发生异常: + e); e.printStackTrace( ); ,im

46、port java.io.*; public class Test public static void main(String argv) ; /创建Test对象,对象名为t System.out.println(t.fliton(); public int fliton() try /第10行的含义是: FileInputStream din = new FileInputStream(test.txt); din.read(); catch(IOException ioe) /第12行的含义是: System.out.println(one); return -1; finally Sy

47、stem.out.println(two); return 0; 如果文件test.txt与Test.java在同一个目录下,test.txt中仅有一行字符串“hello world!”,运行结果是什么?,练习1:阅读下面的程序Test.java,先填写空格的内容,然后写出运行结果:,练习2:文件拷贝,编写一个拷贝任意类型文件的类程序CopyFile.java,该类就只有一个方法copy(),方法声明如下: public boolean copy(String fromFileName, String toFileName,boolean override) 其中,参数1:fromFileNa

48、me 源文件名;参数2:toFileName 目标文件名;参数3: override 目标文件存在时是否覆盖。若文件拷贝成功,则copy()方法返回true,否则返回false。,class CopyFile public boolean copy(String fromFileName, String toFileName,boolean override) File fromFile = new File(fromFileName); File toFile = new File(toFileName); if (!fromFile.exists() | !fromFile.isFile(

49、) | !fromFile.canRead() return false; if (toFile.isDirectory() toFile = new File(toFile, fromFile.getName(); if (toFile.exists() if (!toFile.canWrite() | override = false) return false; else String parent = toFile.getParent(); if (parent = null) parent = System.getProperty(user.dir); File dir = new

50、File(parent); if (!dir.exists() | dir.isFile() | !dir.canWrite() return false; ,FileInputStream from = null; FileOutputStream to = null; try from = new FileInputStream(fromFile); to = new FileOutputStream(toFile); byte buffer = new byte4096; int bytes_read; while ( (bytes_read = from.read(buffer) !=

51、 -1) to.write(buffer, 0, bytes_read); return true; catch (IOException e) return false; ,finally if (from != null) try from.close(); catch (IOException e) if (to != null) try to.close(); catch (IOException e) ,练习3,编写一个程序,统计给定文件中包含的每个单词出现的频率,并按单词表的顺序显示统计结果。,import java.util.*; import java.io.*; public

52、 class testWordCount private String word; private int wordNum; public testWordCount(String wordStr,int num) word=wordStr; wordNum=num; public static void main(String args) String fileName=WordCount.txt; try BufferedReader br = new BufferedReader(new FileReader(fileName); String line = br.readLine();

53、 StringBuffer filecontent=new StringBuffer(); while(line!=null) filecontent.append(line); line = br.readLine(); WordCount(filecontent.toString(); br.close(); catch (Exception ex) ex.printStackTrace(); ,static void WordCount(String filename) String str=filename; String str1=str.replaceAll(a-zA-Z, );

54、StringTokenizer st=new StringTokenizer(str1, ); int j=st.countTokens(); ArrayList wordcount=new ArrayList(); for(int i=0;ij;i+) wordcount=wordSort(wordcount,st.nextToken().toLowerCase(); /output wordCount results for(int i=0;iwordcount.size();i+) System.out.println(testWordCount)wordcount.get(i).wor

55、d +: +(testWordCount)wordcount.get(i).wordNum); static String readFileContent(String filename) StringBuffer buf = new StringBuffer(); try BufferedReader br = new BufferedReader(new FileReader(filename); String line = br.readLine(); while(line!=null) buf.append(line); br.close(); catch (Exception ex)

56、 ex.printStackTrace(); /catch return buf.toString(); ,static ArrayList wordSort(ArrayList a,String aWord) testWordCount wordArray=new testWordCount(aWord,1); if(a.size()=0;i-) int flag=aWpareTo(testWordCount)a.get(i).word); if(flag=0) wordArray.wordNum=(testWordCount)a.get(i).wordNum+1; wordArray.wo

57、rd=aWord; a.set(i,wordArray); break; /if(flag=0) if(flag0) a.add(i+1,wordArray); break; /if(flag0) if(flag0 /ArrayList wordSort ,小结,复制文件,可用字节输入输出流FileInputStream和FileOutputStream实现,见列3 读写文件内容,可用BufferedReader和BufferedWriter实现,见例6 从键盘读取输入, 可用BufferedReader或java.util.Scanner实现,见列6 BufferedReader keyIn=new BufferedReader(new InputStreamR

温馨提示

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

最新文档

评论

0/150

提交评论