java输入输出流.ppt_第1页
java输入输出流.ppt_第2页
java输入输出流.ppt_第3页
java输入输出流.ppt_第4页
java输入输出流.ppt_第5页
已阅读5页,还剩79页未读 继续免费阅读

下载本文档

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

文档简介

Java程序设计,Java Programming Fall, 2010,2 /84,Java I/O,Java输入输出简介 java.io File Class RandomAccessFile Class InputStream & OutputStream Reader & Writer FileInputStream & FileOutputStream FileReader & FileWriter BufferedStream,3 /84,I/O,输入(Input)/输出(Output)系统,简称为I/O系统, 对于输入/输出问题,Java将之抽象化为流(Stream)对象来解决,对不同的输入/输出问题,提供了相应的流对象解决的方案。 流式输入输出的特点是数据的获取和发送沿数据序列的顺序进行,即每一个数据都必须等待排在它前面的数据,等前面的数据读入或送出之后才能被读写。,4 /84,java.io 包,java.io包中定义与输入、输出流相关的类和接口,构成了Java语言的I/O框架。 java.io包中定义的各种各样的输入输出流类,它们都是Object类的直接或间接子类,每一个流类代表一种特定的输入或输出流。 import java.io.*;,5/84,流的类结构,流的实现是在java.io包的类层次结构上。 以四个顶层抽象类为基础,衍生出系列具体的类,来完成各种输入/输出。 InputStream,OutputStream:用于字节的读/写。 Reader,Writer:用于文本(字符)的读/写。 实际使用的是它们的子类的对象。,6/84,File Class,Fundamental class: File Represents either a file(文件) or a dir(文件夹) location in a file system Through its pathname A pathname Unix: /usr/java/bin/javac Windows: c:javabinjavac,7/84,Java文件路径的表示: Java约定是用UNIX和URL风格的斜线(/)来作路径分隔符; 如果用Windows/DOS所使用的反斜线( )的约定,则需要在字符串内使用它的转义序列( )。,8/84,import java.io.*; public class Prova public static void main(String arg) System.out.println(File.separator+“ - “+ File.separatorChar+“ - “+ File.pathSeparator+“ - “+ File.pathSeparatorChar); Output (in Windows) - - ; - ; Output (in Unix): / - / - : - :,Testing-separator,9/84,File类,java.io包中的File类提供了获得文件基本信息及文件操作的方法。 通过File类,可以建立与磁盘文件的联系;可以用来获取或设置文件或目录的属性,但不支持从文件里读取数据或者往文件里写数据。 构造方法 File(String filename); File(String directoryPath, String filename); File(File f, String filename);,10/84,File类的常用方法,文件的属性 public boolean canRead():判断文件是否是可读的。 public boolean canWrite():判断文件是否可被写入。 public boolean exits():判断文件是否存在。 public boolean isFile():判断文件是否是一个正常文件,而不是目录。 public boolean isDirectroy():判断文件是否是一个目录。,11/84,File类的常用方法,获取文件的名称、路径 public String getName():获取文件的名字。 public String getPath():得到文件的路径名。 public String getAbsolutePath():得到文件的绝对路径名。 public String getParent():得到文件的上一级目录名。,12/84,File类的常用方法,获取文件处理信息 public long length(): 获取文件的长度(单位是字节)。 public long lastModified():获取文件最后修改时间。 public boolean delete():删除文件。,13/84,File类的常用方法,目录操作 创建一个名为File的目录: public boolean mkdir() 列出目录中的文件 public String list() public File listFiles() 在目录中创建文件 public boolean createNewFile(),14/84,/创建文件夹和文件 File file2 = new File(“e:/java“); File file1 = new File(file2,“test.txt“); file2.mkdir(); file1.createNewFile();,File files = file2.listFiles(); for(int i = 0; ifiles.length; i+) System.out.println(filesi.getName()+“t“+ filesi.length();,/显示文件夹中所有文件的文件名 String files = file2.list(); for(int i = 0; ifiles.length; i+) System.out.print(filesi);,15/84,Example 1 to test the methods of File,import java.io.File; public class TryFile public static void main(String args) / Create an object that is a directory File myDir = new File(“C:/jdk1.5.0/src/java/io”); System.out.println(myDir + (myDir.isDirectory() ? “ is” : “ is not”) + “ a directory.”); / Create an object that is a file File myFile = new File(myDir, “File.java”); System.out.println(myFile + (myFile.exists() ? “ does” : “ does not”) + “ exist”); System.out.println(myFile + (myFile.isFile() ? “ is” : “ is not”) + “ a file.”); System.out.println(myFile + (myFile.isHidden() ? “ is” : “ is not”) + “ hidden”); System.out.println(“You can” + (myFile.canRead() ? “ “ : “not “) + “read “ + myFile); System.out.println(“You can” + (myFile.canWrite() ? “ “ : “not “) + “write “ + myFile); return; ,16/84,文件的随机访问类(RandomAccessFile),RandomAccessFile类可以对文件进行随机读写操作。 创建一个RandomAccessFile对象 RandomAccessFile(File file,String mode) RandomAccessFile(String name,String mode);,File filenew File(“d:lxa.txt”); RandomAccessFile rf=new RandomAccessFile( file, ”rw”) ; RandomAccessFile rfile=new RandomAccessFile(“d:lxa.txt”, ”rw”);,moder:只读;rw:可读可写 可能产生FileNotFoundException及IOException异常,17/84,文件的随机访问类(RandomAccessFile),读写数据的常用方法 读、写基本数据类型: readInt()、writeInt(int n)等; 读、写UTF字符串: readUTF()、writeUTF(String str); 读取文件中的一行: readLine(); 文件随机读写流的读取指针控制 long getFilePointer() -得到当前的文件读取指针。 void seek(long pos) -把指针从开始移动到pos位置。 long length() -得到文件的长度(有多少个字节) 。 void setLength(long newLength),18 /84,What is the stream? (什么是流?),流是数据的有序序列。 流可分为输入流和输出流(按流动方向) : 输入流指从某个数据来源输入的数据序列, InputStream和Reader处理输入 输出流指将向某个数据目的地输出的数据序列, OutputStream和Writer处理输出,19 /84,输入流、输出流,输入流、输出流分别如下图所示。,输入流示意图,输出流示意图,20 /84,标准流- System Class,java.lang You do not instantiate the System class to use it. All of Systems variables and methods are class variables and class methods. They are declared static. To use a class variable, you use it directly from the name of the class using Javas dot (.) notation.,21 /84,标准流- System Class,class UserNameTest public static void main(String args) String name; name = System.getProperty(““); System.out.println(“Your name is “ + name); Notice that the program never instantiates a System object. It just references the getProperty method and the out variable directly from the class.,22 /84,The Standard I/O Streams,Standard Input Stream System.in - The System class provides a stream for reading text - the standard input stream. Use System.in.read to read the input entered by user. Standard Output and Error Streams System.out - The standard output stream is typically used for command output. System.err - The standard error stream is typically used to display any errors that occur when a program is running. The print, println, and write Methods The print and println methods write their String argument to the screen. System.out.println(“Duke is not a penguin!“); The write method is used to write bytes to the stream. Use write to write non-ASCII data.,23 /84,print and println,print and println methods both take a single argument: Object, String, char, int, long, float, double, and boolean. println takes no arguments and just prints a newline to the stream.,24 /84,/DataTypePrintTest.java public class DataTypePrintTest public static void main(String args) String stringData = “Java Mania“; char charArrayData = a, b, c ; int integerData = 4; long longData = Long.MIN_VALUE; float floatData = Float.MAX_VALUE; double doubleData = Math.PI; boolean booleanData = true; System.out.println(stringData); System.out.println(charArrayData); System.out.println(integerData); System.out.println(longData); System.out.println(floatData); System.out.println(doubleData); System.out.println(booleanData); System.out.println(); ,25 /84,标准流,System类的这3个静态字段就是系统的三个标准流: System.in:表示系统的标准输入流对象,通常的环境下标准输入流指向键盘输入; System.out:表示系统的标准输出流对象,通常环境下指向屏幕输出; System.err:表示系统的标准错误输出流对象,通常环境下也指向屏幕输出。 上述三个标准流由系统负责打开关闭,使用时不需要显式地打开或关闭。 System.out和System.err都用于输出,通常情况下,Syetem.out用于程序输出一般信息,而System.err用于输出错误信息和其他需要引起用户立即注意的信息。在系统中,System.out具有缓冲机制,而System.err是没有缓冲的,这是两者之间的一个重要区别。,26 /84,javac TranslateByte.java java TranslateByte b B,/标准输入、输出 import java.io.*; class TranslateByte public static void main(String args) throws IOException byte from=(byte)args0.charAt(0); byte to=(byte)args1.charAt(0); int b; while(b=System.in.read()!=-1) /read a byte System.out.write(b=from ? to : b); ,输入:abracadabra!,输出:aBracadaBra!,27 /84,28 /84,标准输入输出示例。,import java.io.*; public class StandardIO1 public static void main(String args) int ch; System.out.println(“请输入一行字符“); try while(ch=System.in.read()!=r) System.out.write(ch); catch(IOException e) System.out.println(e.toString(); System.out.write(n); ,29 /84,流的分类,字节流和字符流 InputStream和OutputStream处理8位字节流数据 Reader和Writer处理16位的字符流数据 节点流和处理流(按流的处理位置 ) 节点流:可以从或向一个特定的地方(节点)读写数据。如FileReader 。 处理流:使用节点流作为输入或输出。 处理流不直接与数据源或目标相连,而是与另外的流进行配合,对数据进行某种处理,例如:BufferedReader, InputStreamReader等。,30 /84,字符流和字节流,java.io包中类和接口从功能上主要分为字符流类型和字节流类型 字符(character)流是指数据序列的基本构成单位是16位的Unicode字符数据,如各类基于字符编码的文本文件。 字节(byte)流是指数据序列的基本构成单位是8位的字节数据,如各类基于二进制数据的文件。,31 /84,文本文件(Text Files) vs. 二进制文件(Binary Files),Text file: Three bytes: “1”, “2”, “7” ASCII (binary): 00110001, 00110010, 00110111 Binary file: 非字符文件,如:图片、声音、word文档。,32 /84,How to do I/O,import java.io.*; Open the stream Use the stream (read, write, or both) Close the stream 所有的流类对象在使用前必须打开,在使用后必须关闭,33 /84,字节流(Byte Streams),字节流可分为输入字节流和输出字节流 抽象类 InputStream 用于表示所有输入字节流 抽象类 OutputStream 用于表示所有输出字节流,34 /84,Byte Stream family,Java.lang.System.in,System.out,System.err,35 /84,InputStream和OuputStream两个抽象类的子类,36 /84,InputStream类,该抽象类作为所有输入字节流类的基类,声明用于读取字节流数据的通用方法。 public abstract int read() throws IOException; public int read(byte buf, int offset, int count) throws IOException; public int read(byte buf) throws IOException; public long skip(long count) throws IOException; public int available() throws IOException; public void close() throws IOException; Every method here can throw an IOException; If a programmer uses any of these methods, he/she must catch IOException (or Exception);,37 /84,InputStream类,当创建InputStream类对象时,便自动打开了对象所表示的输入流 InputStream所有与输入相关的方法声明抛出异常类IOException InputStream类的对象在完成数据输入后,除标准输入流类对象System.in外,必须调用close方法关闭输入流,通常可将该方法的调用放入finally语句块中,int b; InputStream stdin1 = System.in; try b = stdin1.read( ); System.out.println(char)b); catch(IOException ie) System.out.println(); ,38/84,/* HelloWorld.java */ import java.io.*; public class HelloWorld public static void main( String args ) byte ba = new byte10; InputStream stdin = System.in; System.out.println(“Please input a string: “); try stdin.read(ba); catch(IOException ie) System.out.println(); String s = new String(ba); System.out.println(“The string read in is “+ s); ,39 /84,OutputStream类,当创建OnputStream类对象时,便自动打开了对象所表示的输出流 OutputStream所有与输出相关的方法声明抛出异常类IOException OutputStream类的对象在完成数据输出后,除标准输出流对象System.out外,必须调用close方法关闭输出流,40 /84,OutputStream类,该抽象类作为所有输出字节流类的基类,声明用于输出字节流数据的通用方法: void write(int b) throws IOException public void write(byte buf, int offset, int count) void write(byte b) throws IOException void flush() throws IOException void close() throws IOException,OutputStream stdout = System.out; stdout.write(104); / ASCII h stdout.flush();,41 /84,字符流(Character Streams),字符流可分为输入字符流和输出字符流 抽象类 Reader 用于表示所有输入字符流 抽象类 Writer 用于表示所有输出字符流,42 /84,Character Stream Family,43 /84,Reader和Writer的主要子类如下:,44 /84,Reader类,该抽象类作为所有输入字符流类的基类,声明用于读取输入字符文本数据的通用方法: public int read() public abstract int read(char buf, int offset,int count) public int read(char buf) public long skip(long count) public int available() public abstract void close(),45 /84,Writer类,该抽象类作为所有输出字符流类的基类,声明用于输出字符文本数据的通用方法: public void write(int ch); public abstract void write(char buf, int offset, int count); public void write(char buf); public void write(String str, int offset, int count); public void write(String str); public Writer append(char c) public Writer append(CharSequence csq) public Writer append(CharSequence csq, int start, int end) public abstract void flush(); public abstract void close();,46 /84,文件的读写,FileOutputStream/FileInputStream 是抽象类InputStream/OutputStream的子类. 它们生成与文件链接的字节流。 为打开文件,只需创建FileOutputStream/FileInputStream类的一个对象,在构造函数中以参数形式指定文件的名称。,47 /84,文件的读写,FileInputStream类和FileOutputStream类的构造函数是创建一个输入输出的对象,通过引用该对象的读写方法,来完成对文件的输入输出操作。在构造函数中,需要指定与所创建的输入输出对象相连接的文件。 要构造一个FileInputStream对象,所连接的文件必须存在而且是可读的; 构造一个FileOutputStream对象如果输出文件已经存在且可写,该文件内容会被新的输出所覆盖。,48 /84,FileInputStream类,从InputStream中派生出来,其所有方法都从InputStream类继承而来。 基本操作步骤:1建立文件的输入流对象 2从输入流中读取字节 3关闭流 常用构造方法 public FileInputStream(String name) throws FileNotFoundException public FileInputStream(File file) throws FileNotFoundException 均会抛出FileNotFoundException异常 构造方法参数指定的文件称作输入流的源 FileInputStream fin = new FileInputStream(“c:javatest.java”);,49 /84,FileInputStream: 文件字节流的读取,read方法给程序提供从输入流中读取数据的基本方法。 read方法的格式 public int read() throws IOException 从输入流中顺序读取单个字节的数据,如果已到达文件末尾,则返回 -1 。 public int read(byte b) throws IOException public int read(byte b, int off, int len) throws IOException 把多个字节读到一个字节数组中,返回实际所读的字节数。 read方法将顺序读取流,直到流的末尾或流被关闭(close()方法)。,50/84,Example with FileInputStream,/* class example FileIn.java */ import java.io.*; public class FileIn public static void main(String args) try FileInputStream fin = new FileInputStream(“c:javatest.java”); int input; while (input = fin.read() != -1) System.out.print(char)input); fin.close(); catch(IOException ie) System.out.println(e); ,51 /84,FileOutputStream类,从OutputStream中派生出来,其所有方法都从OutputStream类继承来的。 基本操作步骤: 1建立文件的输出流对象 2向输出流中写字节 3关闭流 常用构造方法 public FileOutputStream(String name) public FileOutputStream(File file) FileOutputStream fout = new FileOutputStream(“c:javatest.java”);,52 /84,FileOutputStream类: 文件字节流的输出,write方法把字节发送给输出流 write方法的格式: public void write(byte b) throws IOException public void write(byte b, int off, int len) throws IOException write方法将顺序地写文件,直到流的末尾或流被关闭(close()方法) 如果输出流要写入数据的文件已经存在,该文件中的数据内容就会被刷新;如果要写入数据的文件不存在,该文件就会被建立。,53/84,/*例:编写程序,接收用户从键盘输入的数据,回车后保存到 文件test.txt中。若用户输入符号#,则退出程序。*/ import java.io.*; public class WriteFile public static void main(String args) byte buffer=new byte128; System.out.println(“请输入数据,回车后保存到文件test.txt“); System.out.println(“输入 # 则退出!“); try FileOutputStream f=new FileOutputStream(“test.txt“); while(true) int n=System.in.read(buffer); if(buffer0=# ) break; f.write(buffer,0,n); f.write(n); f.close(); catch(IOException e) System.out.println(e.toString(); ,54/84,上例程序运行结果如图所示,55/84,例:使用FileInputStream类与FileOutputStream类复制文件。,/* class example FileIn_Out.java */ /* assumes each char is a single byte */ import java.io.*; public class FileIn_Out public static void main(String args) try FileInputStream fin=new FileInputStream(“c:javafile1.java”); FileOutputStream fout=new FileOutputStream(“c:javafile2.java”); byte b= new byte512; while(fin.read(b,0,512)!=-1) fout.write(b); fin.close(); fout.close(); catch(IOException ie) System.out.println(ie); catch(Exception e) System.out.println(e); ,56/84,7.3 File I/O,/File and File Stream - FileStream.java import java.io.*; class filestream public static void main(String args) try File inFile=new File(”file1.txt“); File outFile=new File(”file2.txt“); FileInputStream fis=new FileInputStream(inFile); FileOutputStream fos=new FileOutputStream(outFile); int c; while(c=fis.read()!=-1) fos.write(c); fis.close(); fos.close(); catch(FileNotFoundException e) System.out.println(“FileStreamsTest: “+e); catch(IOException e) System.err.println(“FileStreamsTest: “+e); ,57 /84,文件I/O FileReader&FileWriter,58 /84,FileReader类,从InputStreamReader中派生出来,其所有方法都从InputStreamReader类和Reader类继承而来。 基本操作步骤: 1建立文件的输出流对象 2向输出流中写字符 3关闭字符流 常用构造方法 public FileReader(String name) throws FileNotFoundException public FileReader (File file) throws FileNotFoundException 均会抛出FileNotFoundException异常 构造方法参数指定的文件称作输入流的源,59 /84,FileReader类:文件字符流的读取,read方法给程序提供从输入流中读取数据的基本方法。 read方法的格式: public int read() throws IOException 从源中顺序读取一个字符 public int read(char ch) throws IOException public int read(char ch, int off, int len) throws IOException 把多个字符读到一个字符数组中,返回实际所读的字符数。,60/84,/FileIn.java import java.io.*; class FileIn public static void main(String args) throws IOException int i; FileReader fr; try fr = new FileReader(“D:workspacetestFileIn.java“); while(i = fr.read()!= -1) System.out.print(char) i); fr.close(); catch(FileNotFoundException e) System.out.println(“File Not Found“); catch(ArrayIndexOutOfBoundsException e) System.out.println(“Usage: ShowFile File“); ,61/84,/FileReaderSample.java import java.io.*; public class FileReaderSample public static void main(String args ) throws IOException /建立可容纳1024个字符的数组 char data=new char100; / 建立对象fr FileReader fr=new FileReader(“D:workspacetestcopy.txt“); / 将数据读入字符列表data内 int num=fr.read(data); / 输出在控制台 System.out.println(“Characters read= “+num); for(int i=0; idata.length;i+) System.out.println(“data“+i+“=“+datai); fr.close(); ,62 /84,FileWriter类,从OutputStreamReader中派生出来,其所有方法都从OutputStreamReader类和Writer类继承而来。 基本操作步骤: 1建立文件的输出流对象 2向输出流中写字符 3关闭字符流 常用构造方法 public FileWriter(String name) public FileWriter(File file) 均会抛出FileNotFoundException异常,63 /84,FileWriter类:文件字符流的输出,write方法给程序提供把字符数据写入到输出流的基本方法。 write方法的格式 public void write(char b ) throws IOException public int write(char b , int off, int len) throws IOException public int write(String str) throws IOException public int write(String str, int offset, int len) throws IOException,64 /84,BufferedStream缓冲流,BufferedReader和BufferedWriter类被用来从基于字符的输入和输出流中读取和写入文本。 BufferdReader类缓存字符以更高效的读取字符串,数组和文本行。 BufferedWriter类缓存字符以更高效的写入字符串,数组和文本行,65 /84,增加缓冲区流,减少访问硬盘的次数,提高效率,file1.txt,file2.txt,输入流,输出流,输入缓冲区,输出缓冲区,处理,Add BufferedStream to improve performance,BufferedStream缓冲流,66 /84,缓冲流-BufferedReader类,Reader类的直接子类 构造方法 public BufferedReader(Reader in, int sz) /sz为缓冲区的大小 public BufferedReader(Reader in) BufferedReader对象的创建 先创建一个Reader子类的对象,然后使用这个对象来创建缓冲流对象。,FileReader inOne = new FileReader(“Student.txt“); BufferedReader inTwo = new BufferedReader(inOne);,任何Reader流都可以用来包装成缓冲流,67 /84,缓冲流的读取 public int read() throws IOException 读取一个字符 public int readLn() throws IOException 读取一行文本,读取完毕后,最好调用close()方法关闭流。,从缓冲区读取,缓冲流-BufferedReader类,68 /84,BufferedWriter类,Writer类的直接子类 构造方法 public BufferedWriter(Writer in,int sz) public BufferedWriter(Reader in) BufferedWriter对象的创建 先创建一个Writer子类的对象,然后使用这个对象来创建缓冲流对象。,FileWriter outOne = new FileWriter(“Student.txt“); BufferedWriter outTwo = new BufferedWriter(outOne);,69 /84,BufferedWriter类,缓冲流的写入 public void write(String str) throws IOException 向缓冲区写入一个字符串。 public int writeLn(String str,int off,int len) throws IOException 向缓冲区写入一个字符串的一部分。 输出完毕后,最好调用close()方法关闭流。,70/84,/*ReadWriteFile.java-读出1.txt中的内容,写入2.txt中 */ import java.io.*; public class ReadWriteFile public static void main(String args) try File read = new File(“c:1.txt”); File write = new File(“c:2.txt”); BufferedReader br = new BufferedReader(new FileReader(read); BufferedWriter bw = new BufferedWriter(new FileWriter(write); String temp = null; temp = br.readLine(); while(t

温馨提示

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

评论

0/150

提交评论