




版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领
文档简介
1、1,8.1 数据流的基本概念,8.4 字符流,8.2 字节流初步,8.3 文件操作,8.5 字符流的高级应用,Stream: one dimension, one direction,2,java.io包简介,从键盘读取数据 从文件中读取数据 写入数据到文件中,读取数据,3,操作文件或目录,什么是文件? 文件可以认为是相关记录或存放在一起的数据的集合。 文件保存在哪里? 文件一般存放在硬盘、光碟或软盘里面。 java中处理文件的类是什么? java提供了java.io包,包中的类可以对文件进行读写操作。,文件,4,File 类,File类提供了创建文件、获取文件属性的机制。 一个File类的对
2、象,表示了磁盘上的文件或目录。 File类提供了与平台无关的方法来对磁盘上的文件或目录进行操作。 File类对象不能直接对文件读写,只能查看文件的属性。,5,import java.io.File; public class FileDemo public static void main(String args) /在当前目录下创建一个与aaa.txt文件名相关联的文件对象 File f1 = new File(aaa.txt); /指明详细的路径以及文件名,请注意双斜线 File f2 = new File(D:JavaHello.java); ,6,Obtaining file prop
3、erties and manipulating file,7,8,File类的构造方法,public File( String path ); public File( String path,String name ); public File( File parentdir, String childdirname );,第一个构造方法从所给的完全路径名建立一个File对象; 第二个从一个单独的路径名和文件创建对象; 第三个构造方法,从一个单独的路径和文件名创建对象,这个路径是和另个File对象相连的。,9,import java.io.*; public class FileTest p
4、ublic static void main(String args) throws Exception File f=new File(1.txt); f.createNewFile(); /File f=new File(1); /f.mkdir(); /File f=new File(D:Myjava1.txt); /f.createNewFile(); ,Case Study: FileTest.java,10,为了做到程序的平台无关性,java中提供了一个常量来表 示目录的分隔符:separator,import java.io.*; public class FileTest pu
5、blic static void main(String args) throws Exception File fDir=new File(File.separator); String strFile=Myjava+File.separator+1.txt; File f=new File(fDir,strFile); f.createNewFile(); ,Case Study: FileTest.java,11,获取文件的名称、路径,String getName( ) 得到文件的名字 String getPath( ) 得到文件的路径名 String getAbsolutePath(
6、) 得到文件的绝对路径名 String getParent( ) 得到文件的上一级目录名 String renameTo( File newName ) 更改文件名,12,测试文件的属性,boolean exists( ) 检查File文件是否存在 boolean canWrite( ) 返回当前文件是否可写 boolean canRead( ) 返回当前文件是否可读 boolean isFile( ) 检测是否是文件 boolean isDirectory( ) 检测是否是目录,13,取文件信息、文件处理工具 long lastModified( ) 返回指定文件的最后被修改时间 long
7、length( ) 返回指定文件的字节长度 boolean delete( ) 删除文件或文件目录 void deleteOnExit( ) 当JVM终止时自动删除文件 目录操作 boolean mkdir( ) 创建指定目录 String list( ) 返回目录中的所有文件名字符串 String list(FilenameFilterfilter) File listFiles() 返回目录中的所有文件对象,14,boolean accept(Filedir, Stringname)测试文件是否应该包含在文件列表当中。 若返回值为真,则包含在文件列表中; 若返回值为假,则不包含在文件列表中
8、。 dir - 文件所在目录 name - 文件名,public interface FilenameFilter,String,int indexOf(String str) 在String对象中查找子串,如果子串存在,返回该子串的索引值, 若该子串不存在,返回-1。,15,import java.io.*; class FileTest public static void main(String args) throws Exception File fDir=new File(File.separator); String strFile=【教学】+File.separator+【Ja
9、va】 +File.separator+【my own】+File.separator+case; File f=new File(fDir,strFile); String names=f.list(new FilenameFilter() public boolean accept(File dir,String name) return name.indexOf(.java)!=-1; ); for(int i=0;inames.length;i+) System.out.println(namesi); ,Case Study: FileTest1.java,16,Class file
10、 is not file (its a direction),Case study: DirList.java DirList2.java DirList3.java,17,import java.io.*; import java.util.*; public class DirList public static void main(String args) try File path = new File(.); String list; if(args.length = 0) list = path.list(); else list = path.list(new DirFilter
11、(args0); for(int i = 0; i list.length; i+) System.out.println(listi); catch(Exception e) e.printStackTrace(); class DirFilter implements FilenameFilter String str1; DirFilter(String str1) this.str1=str1; public boolean accept(File dir, String name) String f=new File(name).getName(); return f.indexOf
12、(str1)!=-1; ,DirList.java,18,import java.io.*; public class DirList2 public static FilenameFilter filter(final String afn) return new FilenameFilter() / Creation of anonymous inner class: String fn = afn; public boolean accept(File dir, String n) / Strip path information: String f = new File(n).getN
13、ame(); return f.indexOf(fn) != -1; ; / End of anonymous inner class public static void main(String args) try File path = new File(.); String list; if(args.length = 0) list = path.list(); else list = path.list(filter(args0); for(int i = 0; i list.length; i+) System.out.println(listi); catch(Exception
14、 e) e.printStackTrace(); ,DirList2.java,19,import java.io.*; public class DirList3 public static void main(final String args) try File path = new File(.); String list; if(args.length = 0) list = path.list(); else list = path.list( new FilenameFilter() public boolean accept(File dir, String n) String
15、 f = new File(n).getName(); return f.indexOf(args0) != -1; ); for(int i = 0; i list.length; i+) System.out.println(listi); catch(Exception e) e.printStackTrace(); ,DirList3.java,20,I/O流,内 存,数据,写文件,读文件,数据,数据,把内存中的数据写到文件,将文件中的数据读到内存,21,J,A,V,I/O流的顺序,A,流,流是以先进先出的方式发送和接收数据的通道,22,I/O流的分类-1,根据流动方向分类: 应用程序
16、从目标外设读取数据的流称为输入流。 应用程序向目标外设写入数据的流称为输出流。,23,输入输出流,流是指在计算机的输入输出之间运动的数据序列 输入流代表从外设流入计算机的数据序列; 输出流代表从计算机流向外设的数据序列。,24,25,How is I/O Handled in Java?,A File object encapsulates the properties of a file or a path, but does not contain the methods for reading/writing data from/to a file. In order to perfor
17、m I/O, you need to create objects using appropriate Java I/O classes.,FileWriter output = new FileWriter(temp.txt); output.write(Java 101); output.close();,FileReader input = new FileReader(temp.txt); int code = input.read(); System.out.println(char)code);,26,节点流:从特定的地方读写的流类,例如:磁盘或一块内存区域。 过滤流:使用节点流作
18、为输入或输出。过滤流是使用一个已经存在的输入流或输出流连接创建的。,27,Coding Essentials,28,流式输入输出的特点,每个数据都必须等待排在它前面的数据读入或送出之后才能被读写,每次读写操作处理的都是序列中剩余的未读写数据中的第一个,而不能随意选择输入输出的位置。,I/O包字节流的类层次图,29,30,Text File vs. Binary File,Data stored in a text file are represented in human-readable form. Data stored in a binary file are represented i
19、n binary form. You cannot read binary files. Binary files are designed to be read by programs. The advantage of binary files is that they are more efficient to process than text files. Although it is not technically precise and correct, you can imagine that a text file consists of a sequence of char
20、acters and a binary file consists of a sequence of bits. For example, the decimal integer 199 is stored as the sequence of three characters: 1, 9, 9 in a text file and the same integer is stored as a byte-type value C7 in a binary file, because decimal 199 equals to hex C7.,31,Binary I/O,Text I/O re
21、quires encoding and decoding. The JVM converts a Unicode to a file specific encoding when writing a character and coverts a file specific encoding to a Unicode when reading a character. Binary I/O does not require conversions.,32,Binary I/O Classes,33,The value returned is a byte as an int type.,Inp
22、utStream,34,InputStream类的主要方法,read():往流中读入数据,只能读字节 int read() 简单的从流中读单字节整数, 若读到了输入流的末尾,则返回值-1; read(byte b) 读多个字节到字节数 组,返回实际读到的字节数; read(byte b,int off, int len)读数据到 字节数组并放到数组中的某 个范围(off表示数组索引;len 表示读取字符数),35,int available() 返回当前流中可用的字节数 mark() 在流中标记一个位置 skip(long n) 跳过流中的若干字节 void reset() 返回标记过的位置
23、boolean markSupported() 有些流不支持mark void close() 关闭这个流,释放和流相关的 系统资源,InputStream类的主要方法,36,java.io包中 InputStream的类层次,37,Kind of InputStream(only read byte),ByteArrayInputStream StringBufferInputStream FileInputStream PipedInputStream SequenceInputStream,38,The value is a byte as an int type.,OutputStre
24、am,39,OutputStream类的主要方法,write():将数据写入流中 void write(int b); 简单的写一个字节到流 void write(byte b); 数组中所有字节写到流 void write(byte b,int off, int len);将字符数 组按指定的格式输出到流中(off表示数组索 引;len表示写入字符数) close(): 关闭这个流 flush(): 刷新输出流,40,java.io包中 OutputStream的类层次,41,基 本 的 流 类,FileInputStream和FileOutputStream 节点流,用于从文件中读取或往文
25、件中写入字节流。如果在构造 FileOutputStream时,文件已经存在,则覆盖这个文件。 BufferedInputStream和BufferedOutputStream 过滤流,需要使用已经存在的节点流来构造,提供带缓冲的读写,提高 了读写的效率。 DataInputStream和DataOutputStream 过滤流,需要使用已经存在的节点流来构造,提供了读写Java中的基本 数据类型的功能。 PipedInputStream和PipedOutputStream 管道流,用于线程间的通信。一个线程的PipedInputStream对象从另一 个线程的PipedOutputStrea
26、m对象读取输入。要使管道流有用,必须同时构 造管道输入流和管道输出流。,42,FileInputStream/FileOutputStream,FileInputStream/FileOutputStream associates a binary input/output stream with an external file. All the methods in FileInputStream/FileOuptputStream are inherited from its superclasses.,43,FileInputStream,To construct a FileInpu
27、tStream, use the following constructors: public FileInputStream(String filename) public FileInputStream(File file) A java.io.FileNotFoundException would occur if you attempt to create a FileInputStream with a nonexistent file.,44,45,46,如果用户的文件读取需求比较简单,那么可以使用 FileInputStream 类,该类是从InputStream中派生出来的,其
28、中的所有方法都是从InputStream类继承来的。基本操作步骤: 建立文件的输入流对象 从输入流中读取字节 关闭流,FileInputStream,47,import java.io.*; public class FileApp public static void main(String args) byte buffer=new byte2056; try FileInputStream fileIn= new FileInputStream(d:testParcel4.java); int bytes=fileIn.read(buffer,0,2056); String str=ne
29、w String(buffer,0,bytes); System.out.println(str); catch(Exception e) String err=e.toString(); System.out.println(err); ,Case study: FileApp.java,48,FileOutputStream,To construct a FileOutputStream, use the following constructors: public FileOutputStream(String filename) public FileOutputStream(File
30、 file) public FileOutputStream(String filename, boolean append) public FileOutputStream(File file, boolean append) If the file does not exist, a new file would be created. If the file already exists, the first two constructors would delete the current contents in the file. To retain the current cont
31、ent and append new data into the file, use the last two constructors by passing true to the append parameter.,49,50,51,OutputStream类的主要方法,write():将数据写入流中 void write(int b); 简单的写一个字节到流 void write(byte b); 数组中所有字节写到流 void write(byte b,int off, int len);将字符数 组按指定的格式输出到流中(off表示数组索 引;len表示写入字符数) close():
32、 关闭这个流 flush(): 刷新输出流,52,FileApp2.java,如果用户输出到文件中的内容比较简单,那么可以使用 FileOutputStream 类 , 该类是从OutputStream中派生出来的,其中的所有方法都是从OutputStream类继承来的。基本操作步骤: 建立文件的输出流对象 把字节写到输出流中 关闭流,FileOutputStream,53,import java.io.*; public class FileApp2 public static void main(String args) byte buffer=new byte80; try System
33、.out.println(nEnter a line to be saved to disk:); int bytes=System.in.read(buffer); FileOutputStream fileOut=new FileOutputStream(d:line.txt); fileOut.write(buffer,0,bytes); catch(Exception e) String err=e.toString(); System.out.println(err); ,Case study: FileApp2.java,54,FilterInputStream/FilterOut
34、putStream,Filter streams are streams that filter bytes for some purpose. The basic byte input stream provides a read method that can only be used for reading bytes. If you want to read integers, doubles, or strings, you need a filter class to wrap the byte input stream. Using a filter class enables
35、you to read integers, doubles, and strings instead of bytes and characters. FilterInputStream and FilterOutputStream are the base classes for filtering data. When you need to process primitive numeric types, use DatInputStream and DataOutputStream to filter bytes.,55,Filtered Stream,DataInputStream
36、DataOutputStream LineNumberInputStream PrintStream BufferedInputStream BufferedOutputStream PushbackInputStream,56,过滤器流,可以提高I/O操作的效率。,BufferedInputStream,BufferedOutputStream,57,缓冲流,使用缓冲流提高对外设数据读写的速度。 BufferedInputStream提高读取速度。 BufferedOutputStream提高写入的速度。,58,import java.io.*; public class BufferedD
37、emo public static void main(String args) try String str = new String(天苍苍,地茫茫,风吹草低见牛羊!); /通过文件名创建文件输出流对象 FileOutputStream fos = new FileOutputStream(testWriter.txt); /创建缓冲流 BufferedOutputStream bos=new BufferedOutputStream(fos); /将字符串转化为字节数组 byte buf = str.getBytes(); bos.write(buf); /将字节数组中包含的数据一次性写
38、入文件中 bos.flush(); /刷新将缓冲区中的数据提交 bos.close(); /关闭流 System.out.println (数据成功写入文件); catch (IOException ioe) ioe.printStackTrace(); ,Case study: BufferedDemon.java,59,About JAR,JAR(库)是一个独立于平台的文件格式, 它允许将许多文件集成为一个文件,并可 以直接执行。,60,Compress,Case study: GZIPcompress.java,61,import java.io.*; import java.util.
39、zip.*; public class GZIPcompress public static void main(String args) try BufferedReader in=new BufferedReader(new FileReader(“d:line.txt”); BufferedOutputStream out=new BufferedOutputStream(new GZIPOutputStream(new FileOutputStream(test.gz); System.out.println(Writing file.); int c; while(c=in.read
40、()!=-1) out.write(c); in.close(); out.close(); System.out.println(Reading file.); BufferedReader in2=new BufferedReader(new InputStreamReader(new GZIPInputStream(new FileInputStream(test.gz); String s; while(s=in2.readLine()!=null) System.out.println(s); catch(Exception e)e.printStackTrace(); ,GZIPc
41、ompress.java,62,DataInputStream/DataOutputStream,DataInputStream reads bytes from the stream and converts them into appropriate primitive type values or strings.,DataOutputStream converts primitive type values or strings into bytes and output the bytes to the stream.,63,DataInputStream流处理器可以把FileInp
42、utStream流对象的输出当作输入,将Byte类型的数据转换成Java的原始类型和String类型的数据。,DataInputStream,64,DataInputStream,DataInputStream extends FilterInputStream and implements the DataInput interface.,65,66,DataInputStream读取二进制文件,/将文件输入流包装成数据输入流,以便从文件中读取各种类型的数据 FileInputStream fis = new FileInputStream(data.dat); DataInputStrea
43、m dis = new DataInputStream(fis);,DataInputStream是一个包装流,在创建其它实例对象需要包装一个节点流对象,DataInputStream类可以输入任何类型的数据,但它不可以单独使用,需要配合其它字节输入流一起使用,67,一个程序需要向一个文件里写入的数据往往都是结构化的,而Byte类型则是原始类型。因此在写的时候必须经过转换。DataOutputStream流处理器接收原始数据类型和String数据类型,而这个流处理器的输出数据则是Byte类型。,DataOutputStream,68,DataOutputStream,DataOutputStr
44、eam extends FilterOutputStream and implements the DataOutput interface.,69,70,DataOutputStream写二进制文件,/将文件输出流包装成数据输出流,以便往文件中写入各种类型的数据 FileOutputStream fos = new FileOutputStream(data.dat); DataOutputStream dos = new DataOutputStream(fos);,DataOutputStream是一个包装流,在创建其它实例对象需要包装一个节点流对象,实例学习,71,import jav
45、a.io.*; class StreamTest public static void main(String args) throws Exception FileOutputStream fos=new FileOutputStream(1.txt); BufferedOutputStream bos=new BufferedOutputStream(fos); DataOutputStream dos=new DataOutputStream(bos); byte b=3; int i=78; char ch=a; float f=4.5f; dos.writeByte(b); dos.
46、writeInt(i); dos.writeChar(ch); dos.writeFloat(f); dos.close(); FileInputStream fis=new FileInputStream(1.txt); BufferedInputStream bis=new BufferedInputStream(fis); DataInputStream dis=new DataInputStream(bis); System.out.println(dis.readByte(); System.out.println(dis.readInt(); System.out.println(
47、dis.readChar(); System.out.println(dis.readFloat(); dis.close(); ,StreamTest.java,72,8.2 字节流初步,管道流,管道流用来在线程间进行通信。一个线程的PipedInputStream对象从另一个线程的PipedOutputStream对象读取输入。要使管道流有用,必须有一个输入方和一个输出方。,73,8.2 字节流初步,74,class Sender implements Runnable OutputStream out; public Sender(OutputStream out) this.out=o
48、ut; public void run() byte value; try for(int i=0;i5;i+) value=(byte)(Math.random()*256); System.out.println(About to send +value+. ); out.write(value); System.out.println(.send.); Thread.sleep(long)(Math.random()*1000); out.close(); catch(Exception e) e.printStackTrace(); ,75,class Receiver impleme
49、nts Runnable InputStream in; public Receiver(InputStream in) this.in=in; public void run() int value; try while(value=in.read()!=-1) System.out.println(received +(byte)value+.); System.out.println(Piped closed.); catch(Exception e) e.printStackTrace(); ,76,public class Pipe public static void main(S
50、tring args) throws Exception PipedInputStream in=new PipedInputStream(); PipedOutputStream out=new PipedOutputStream(in); Sender s=new Sender(out); Receiver r=new Receiver(in); Thread t1=new Thread(s); Thread t2=new Thread(r); t1.start(); t2.start(); t2.join(); ,Case Study: Pipe.java,77,Java I/O库的设计
51、原则,Java的I/O库提供了一个称做链接的机制,可以将一个流与另 一个流首尾相接,形成一个流管道的链接。 这种机制实际上是 一种被称为Decorator(装饰)设计模式的应用。 通过流的链接,可以动态的增加流的功能,而这种功能的增 加是通过组合一些流的基本功能而动态获取的。 我们要获取一个I/O对象,往往需要产生多个I/O对象,这也是 Java I/O库不太容易掌握的原因,但在I/O库中Decorator模式 的运用,给我们提供了实现上的灵活性。,78,Input Stream Chain,Output Stream Chain,I/O流的链接,79,Text I/O Classes,80,
52、Reader class StreamTest public static void main(String args) throws Exception FileOutputStream fos=new FileOutputStream(1.txt); OutputStreamWriter osw=new OutputStreamWriter(fos); BufferedWriter bw=new BufferedWriter(osw); bw.write(); bw.close(); FileInputStream fis=new FileInputStream(1.txt); Input
53、StreamReader isr=new InputStreamReader(fis); BufferedReader br=new BufferedReader(isr); System.out.println(br.readLine(); br.close(); ,实例学习,StreamTest1.java,86,FileReader/FileWriter,FileReader/FileWriter associates an input/output stream with an external file. All the methods in FileReader/FileWrite
54、r are inherited from its superclasses.,87,FileReader,To construct a FileReader, use the following constructors: public FileReader(String filename) public FileReader(File file) A java.io.FileNotFoundException would occur if you attempt to create a FileReader with a nonexistent file.,88,文件的读取使用FileRea
55、der类,要使用FileReader类读取文件,必须先调用FileReader()构造函数产生FileReader类的对象,再利用它来调用read()方法。 FileReader(String name) 依文件名称创建一个可读取字符的输入流对象。,89,import java.io.*; public class App public static void main(String args)throws java.io.IOException char data=new char1024; FileReader fr=new FileReader(“d:donkey.txt”); int
56、num=fr.read(data); String str=new String(data,0,num); System.out.println(“Characters read=”+num); System.out.println(str); fr.close(); ,Case Study: App.java,90,FileWriter,To construct a FileWriter, use the following constructors: public FileWriter(String filename) public FileWriter(File file) public
57、 FileWriter(String filename, boolean append) public FileWriter(File file, boolean append) If the file does not exist, a new file would be created. If the file already exists, the first two constructors would delete the current contents in the file. To retain the current content and append new data into the file, use the last two constructors by passing true to the append parameter.,91,文件的写入使用FileWriter类,要使用FileWriter类写入文件,必须先调用FileWriter()构造函数产生FileWriter类的对象,再利用它来调用Write()方法。 FileWriter(String filename) 依文件名称创建一个可供写入字符数据的输出流
温馨提示
- 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
- 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
- 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
- 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
- 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
- 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
- 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。
最新文档
- 2025年瓦斯设备项目深度研究分析报告
- 2025-2030年中国线路铁附件行业深度研究分析报告
- 2025-2030年中国牵切线项目投资可行性研究分析报告
- 2025-2030年中国高效低烟无卤阻燃剂行业深度研究分析报告
- 2025年厚、薄膜混合集成电路及消费类电路项目构思建设方案
- 教育培训项目进度管理方案
- 2025年物流行业安全培训方案
- 医疗救助贷款合同特别约定
- 钢结构项目承包合同标准范本
- 围墙改造工程合同书
- 精细化工工艺学-第1章绪论讲解课件
- 仰拱栈桥计算
- 中医妇科 月经过多课件
- 2022年江西制造职业技术学院单招语文试题及答案解析
- 穆斯林太巴热咳庆念词文
- 商标一级授权书模板
- 软硬结合板的设计制作与品质要求课件
- 民营医院组织架构图示
- 慢性心功能不全护理查房
- 初中 初二 物理 凸透镜成像规律实验(习题课) 教学设计
- 消防维保方案 (详细完整版)
评论
0/150
提交评论