《JAVA语言程序设计》第9章.ppt
1Java I/O操作n概念nJava I/O类nJava I/O操作n标准输入/输出n文件读写操作n目录管理n随机访问文件n文件属性2概念nI/O来源n控制台(console,如DOS窗口)打印/读入n文件(file)读/写n网络接口(TCP/UDP端口)读/写n针对数据的读写n以流(stream)的方式对数据进行操作数据源程序读出数 据流目的程序写入数 据流流的重要特性n顺序读/写nsequentially3概念n读/写流的一般流程n读(Reading)1.open a stream /打开读出流2.while more information /判断3.read information /读4.close the stream /关闭流n写(Writing)1.open a stream /打开写入流2.while more information /判断3.write information /写4.close the stream /关闭流4概念n两种流的定义(读取信息的基本数据单位)n字节流(byte stream):一个字节(8-bit)一个字节读/写n字符流(character stream):一个字符一个字符读/写(具有特定字符编码的数据)j a v a 语 言6A 61 76 61 D3 EF D1 D4以字节流的方式读:读8次,8个字节以字符流的方式读:读6次,6个字符5Java I/O操作n概念nJava I/O类nJava I/O操作n标准输入/输出n文件读写操作n目录管理n随机访问文件n文件属性6Java I/O类n字节流的读/写操作(来自JDK1.0)njava.io.InputStream(抽象类)1.public abstract int read()2.public int read(byte b)3.public int read(byte b,int offset,int length)4.到达流的终点,无数据读出则返回-1njava.io.OutputStream(抽象类)1.public abstract void write(int b)2.public void write(byte b)3.public void write(byte b,int offset,int length)n所有的读/写函数都抛出java.io.IOException7Java I/O类n字符流的读/写操作(来自JDK1.1)njava.io.Reader类(抽象类)1.public int read()2.public int read(char cbuf)3.publc abstract int read(char cbuf,int offset,int length)4.到达流的终点,无数据读出则返回-1njava.io.Writer类(抽象类)1.public void write(int c)2.public void write(char cbuf)3.public void write(char cbuf,int offset,int length)n所有的读/写函数都抛出java.io.IOException8Java I/O类nI/O流的层次关系nclass java.io.InputStream的子类nclass java.io.ByteArrayInputStreamnclass java.io.FileInputStreamnclass java.io.FilterInputStreamnclass java.io.BufferedInputStreamnclass java.io.DataInputStream nclass java.io.LineNumberInputStreamnclass java.io.PushbackInputStreamnclass java.io.ObjectInputStream nclass java.io.PipedInputStreamnclass java.io.SequenceInputStreamnclass java.io.StringBufferInputStreamn 9Java I/O类nI/O流的层次关系nclass java.io.OutputStream的子类nclass java.io.ByteArrayOutputStreamnclass java.io.FileOutputStreamnclass java.io.FilterOutputStreamnclass java.io.BufferedOutputStreamnclass java.io.DataOutputStream nclass java.io.PrintStreamnclass java.io.ObjectOutputStreamnclass java.io.PipedOutputStreamn 10Java I/O类nI/O流的层次关系nclass java.io.Reader的子类nclass java.io.BufferedReadernclass java.io.LineNumberReadernclass java.io.CharArrayReadernclass java.io.FilterReader nclass java.io.PushbackReadernclass java.io.InputStreamReadernclass java.io.FileReadernclass java.io.PipedReadernclass java.io.StringReadern 11Java I/O类nI/O流的层次关系nclass java.io.Writer的子类nclass java.io.BufferedWriternclass java.io.CharArrayWriternclass java.io.FilterWriternclass java.io.OutputStreamWriter nclass java.io.FileWriternclass java.io.PipedWriternclass java.io.PrintWriternclass java.io.StringWritern 12Java I/O类nI/O流的分类(12个功能类)I/O类型所用到的类描述文件FileReader/FileWriterFileInputStream/FileOutputStream文件流(读/写文件)缓冲BufferedReader/BufferedWriterBufferedInputStreamBufferedOutputStream提高读/写效率打印PrintWriter PrintStream(System.out.println()内存CharArrayReader/CharArrayWriterByteArrayInputStreamByteArrayOutputStreamStringReader/StringWriterStringBufferInputStream读/写内存13Java I/O类nI/O流的分类(12个功能类)I/O类型所用到的类描述字节流和字符流的转换InputStreamReaderOutputStreamWriter将InputStream中读入的字节转为字符/将字符转为字节写入OutputStream管道pipePipedReader/PipedWriterPipedInputStream/PipedOutputStream文件流(读/写文件)连接ConcatenationSequenceInputStream多个输入流连接为一个输入流对象串行化ObjectInputStreamObjectOutputStreamObject Serialization14Java I/O类nI/O流的分类(12个功能类)I/O类型所用到的类描述基本数据转化DataInputStreamDataOutputStreamJAVA基本数据类型的读/写计数LineNumberReaderLineNumberInputStream读操作时记录行数Peeking AheadPushbackReaderPushbackInputStream可回退缓存(pushback buffer)过滤FilterReader/FilterWriterFilterInputStream/FilterOutputStream在读/写操作时对数据进行过滤15Java I/O操作n概念nJava I/O类nJava I/O操作n标准输入/输出n文件读写操作n目录管理n随机访问文件n文件属性16Java I/O操作n主要内容1.标准输入/输出n控制台屏幕打印和键盘读入2.文件I/O操作n文件读写n如何提高文件读写效率n流的包装(Wrap)n基本数据转换流n目录管理n随机访问文件(Random Access File)n文件属性3.网络流操作(见第十三讲)17n输出:控制台屏幕打印class Test public static void main(String args)System.out.println(“Hello World!”);标准输入/输出C:java TestHello World!C:18n输入:键盘读入import java.io.IOException;class Test public static void main(String args)throws IOException byte b=new byte10;System.out.println(Received number=+System.in.read(b);标准输入/输出C:java TestAReceived number=3C:19n文件读/写流程1.打开文件流2.条件判断3.读出/写入4.关闭文件流n两种类型文件nFileInputStream/FileOutputStream(字节流)n读取/生成ASCII文件nFileReader/FileWriter (字符流)n读取/生成包括汉字字符的文件文件读写操作201.文件字节流构造方法(打开字节流)n利用java.io.FileInputStream类读取文件npublic FileInputStream(String name)throws FileNotFoundExceptionnpublic FileInputStream(File file)throws FileNotFoundExceptionn利用java.io.FileOutputStream类写/生成文件npublic FileOutputStream(String name)throws FileNotFoundExceptionnpublic FileOutputStream(String name,boolean append)throws FileNotFoundExceptionnpublic FileOutputStream(File file)throws FileNotFoundExceptionnpublic FileOutputStream(File file,boolean append)throws FileNotFoundException /是否向已存在的文件后添加njava.io.File类的构造方法public File(String pathname)文件读写操作21n文件读写-实例1文件读写操作import java.io.*;public class CopyBytes public static void main(String args)throws IOException File inputFile =new File(“original.txt);File outputFile =new File(“result.txt);FileInputStream in =new FileInputStream(inputFile);FileOutputStream out =new FileOutputStream(outputFile);int c;while(c=in.read()!=-1)out.write(c);in.close();out.close();public int read()throws IOExceptionpublic int read(byte b)throws IOExceptionpublic int read(byte b,int off,int len)throws IOExceptionFileInputStream in =new FileInputStream(“original.txt);FileOutputStream out=new FileOutputStream(“result.txt);public void write(int b)throws IOExceptionpublic void write(byte b)throws IOExceptionpublic void write(byte b,int off,int len)throws IOException打开流读取流写入流关闭流222.字符流构造方法(打开字符流)n利用java.io.FileReader读取文件npublic FileReader(String fileName)throws FileNotFoundExceptionnpublic FileReader(File file)throws FileNotFoundExceptionn利用java.io.FileWriter写/生成文件npublic FileWriter(String fileName)throws IOExceptionnpublic FileWriter(String fileName,boolean append)throws IOExceptionnpublic FileWriter(File file)throws IOExceptionnpublic FileWriter(File file,boolean append)throws IOExceptionnjava.io.File类的构造方法public File(String pathname)文件读写操作23n文件读写-实例2文件读写操作import java.io.*;public class Copy public static void main(String args)throws IOException File inputFile =new File(“original.txt);File outputFile=new File(“result.txt);FileReader in =new FileReader(inputFile);FileWriter out =new FileWriter(outputFile);int c;while(c=in.read()!=-1)out.write(c);in.close();out.close();FileReader in =new FileReader(“original.txt);FileWriter out=new FileWriter(“result.txt);public int read()throws IOExceptionpublic int read(char cbuf)throws IOExceptionpublic int read(char cbuf,int off,int len)throws IOExceptionpublic void write(int b)throws IOExceptionpublic void write(char cbuf)throws IOExceptionpublic void write(char cbuf,int off,int len)throws IOException打开流读取流写入流关闭流24n两类缓冲流n针对字节流njava.io.BufferedInputStream类njava.io.BufferedOutputStream类n针对字符流njava.io.BufferedReader类njava.io.BufferedWriter类如何提高文件读写效率25n构造方法njava.io.BufferedInputStream类npublic BufferedInputStream(InputStream in)n默认缓冲字节(2048 bytes)npublic BufferedInputStream(InputStream in,int size)npublic BufferedOutputStream(OutputStream out)n默认缓冲字节(512 bytes)npublic BufferedOutputStream(OutputStream out,int size)njava.io.BufferedReader类npublic BufferedReader(Reader in)n默认缓冲字节(8192 bytes)npublic BufferedReader(Reader in,int sz)npublic BufferedWriter(Writer out)n默认缓冲字节(8192 byte)npublic BufferedWriter(Writer out,int sz)如何提高文件读写效率26 String filename =“test.txt”;FileInputStream fis =new FileInputStream(filename);int count=0;int c;while(c=fis.read()!=-1)if(c=A)count+;fis.close();System.out.println(count);n实例1(判断一个文本文件包含多少个字符A)如何提高文件读写效率普通的文件流27如何提高文件读写效率 String filename =“test.txt”;FileInputStream fis =new FileInputStream(filename);BufferedInputStream bis=new BufferedInputStream(fis);int count=0;int c;while(c=bis.read()!=-1)if(c=A)count+;fis.close();System.out.println(count);利用缓冲流n实例1(判断一个文本文件包含多少个字符A)28如何提高文件读写效率 FileInputStream fis=new FileInputStream(“test.txt”);int count=0;final int BUFSIZE=1024;byte buf=new byteBUFSIZE;int len;while(len=fis.read(buf)!=-1)for(int i=0;i len;i+)if(bufi=A)count+;fis.close();自定义一个缓冲区n实例1(判断一个文本文件包含多少个字符A)29 String filename =“test.txt”;FileReader fr =new FileReader(filename);BufferedReader br=new BufferedReader(fr);int count=0;while(br.readLine()!=null)count+;br.close();System.out.println(count);n实例2(按行读取数据)如何提高文件读写效率30n概述流的包装(wrap)FileReader fr =new FileReader(filename);BufferedReader br=new BufferedReader(fr);String filename=“test.txt”;BufferedReader br=new BufferedReader(new FileReader(filename);PrintWriter out=new PrintWriter(new BufferedWriter(new FileWriter(filename);public String readLine()in java.io.BufferedReader 按行读数据public void println(String x)in java.io.PrintWriter 按行打印数据n利用不同流的特点(方法)n寻找合适的方法完成特定的需求n对已有的流进行再处理31n流的种类n节点流n直接对数据源进行读/写操作的流n处理流n对一个已有的流进行某种操作(进行加工)的流流的包装(wrap)32n节点流nFileInputStream,PipedInputStream,ByteArrayInputStream,StringBufferInputStreamnFileOutputStream,PipedOutputStream,ByteArrayOutputStreamnCharArrayReader,FileReader,PipedReader,StringReadernCharArrayWriter,FileWriter,PipedWriter,StringWriter流的包装(wrap)33n处理流nFilterOutputStream,DataOutputStream,BufferedOutputStream,PrintStreamnFilterInputStream,LineNumberInputStream,DataInputStream,BufferedInputStream,PushbackInputStreamnBufferedReader,LineNumberReader,InputStreamReader,FilterReader,PushBackReadernBufferedWriter,OutputStreamReader,FilterWriter,PrintWriter流的包装(wrap)34n一个实例njava.io.FileReader类npublic FileReader(File file)throws FileNotFoundExceptionnpublic FileReader(String fileName)throws FileNotFoundExceptionnjava.io.BufferedReader类npublic BufferedReader(Reader in)n默认缓冲字节(8192 bytes)npublic BufferedReader(Reader in,int sz)n流的包装改变了流的行为流的包装(wrap)35n实例1(在DOS屏幕上实现回显功能)流的包装(wrap)import java.io.*;public class Echo public static void main(String args)throws IOException BufferedReader in=new BufferedReader(new InputStreamReader(System.in);String s;while(s=in.readLine().length()!=0)System.out.println(s);public static final InputStream in (java.lang.System类)public InputStreamReader(InputStream in)(java.io.InputStreamReader类)public BufferedReader(Reader in)(java.io.BufferedReader类)D:java EchoHelloHelloTestTest D:36n概述njava.io.DataInputStream类读取基本类型的数据npublic DataInputStream(InputStream in)npublic final boolean readBoolean()npublic final byte readByte()npublic final char readChar()npublic final int readInt()njava.io.DataOutputStream类写基本类型的数据npublic DataOutputStream(OutputStream out)npublic final void writeBoolean(boolean v)npublic final void writeByte(int v)npublic final void writeChar(int v)npublic final void writeInt(int v)基本数据转换流处理流 处理流 37DataOutputStream out=new DataOutputStream(new FileOutputStream(invoice.txt);double prices=19.99,9.99;int units=12,8;String descs=Java T-shirt,Java Mug;for(int i=0;i prices.length;i+)out.writeDouble(pricesi);out.writeChar(t);out.writeInt(unitsi);out.writeChar(t);out.writeChars(descsi);out.writeChar(n);out.close();n实例1(写基本类型的数据)基本数据转换流19.99 12 Java T-shirt9.99 8 Java Bag 38n基本数据转换流-实例基本数据转换流DataInputStream in=new DataInputStream(new FileInputStream(invoice.txt);double total;try while(true)double price=in.readDouble();in.readChar();int unit=in.readInt();in.readChar();char chr;StringBuffer desc=new StringBuffer(20);while(chr=in.readChar()!=n)desc.append(chr);System.out.println(price+“+unit+“+desc);total=total+unit*price;catch(EOFException e)System.out.println(total);in.close();19.99 12 Java T-shirt9.99 8 Java Bag 599.68invoice.txt19.99 12 Java T-shirt9.99 8 Java Bag 39n概述njava.io.File类表示文件和目录的路径名n构造方法npublic File(String pathname)npublic File(String parent,String child)npublic File(File parent,String child)nparent通常表示一个目录,child则表示一个目录或文件n路径名(pathname)nUNIX平台上绝对路径的前缀“/”,相对路径无前缀,例“/etc/inetd.conf”、“inetd.conf”nWindows平台,绝对路径名的前缀由“盘符:”组成;UNC 路径名前缀为“”,然后是主机名和共享名,相对路径名无盘符,例“c:windowsnotepad.exe”、“notepad.exe”目录管理40n方法npublic boolean canWrite()/canRead()npublic boolean exists()npublic boolean delete()n删除文件或目录,若删除目录,要求该目录必须为空npublic boolean createNewFile()n创建一个空文件,当且仅当该文件不存在npublic boolean isDirectory()/isFile()/isHidden()npublic long lastModified()/public boolean setLastModified(long time)npublic String list()n得到当前目录下的所有文件名和目录名,若该File对象不是表示目录,则返回nullnpublic boolean mkdir()/mkdirs()n创建一个目录npublic boolean renameTo(File dest)npublic boolean setReadOnly()目录管理41n目录管理方法举例目录管理import java.io.File;public class DirList public static void main(String args)File path=new File(.);String list=path.list();for(int i=0;i list.length;i+)System.out.println(listi);42n随机访问文件(Random Access File)njava.io.RandomAccessFile类n读写操作在同一个类中完成,须在构造对象时指定参数n通过移动文件指针(file pointer)在文件的指定位置进行读写操作n构造方法npublic RandomAccessFile(String name,String mode)throws FileNotFoundExceptionnpublic RandomAccessFile(File file,String mode)throws FileNotFoundExceptionnmode:“r”,“rw”随机访问文件43n方法npublic void seek(long pos)设定文件指针npublic int read()npublic int read(byte b)npublic int read(byte b,int off,int len)npublic final boolean readBoolean()/readByte()/readChar()/readShort()/readInt()/readDouble()/readFloat()npublic final String readLine()npublic void write(int b)npublic void write(byte b)npublic void write(byte b,int off,int len)npublic final void writeBoolean()/writeByte()/writeChar()/writeShort()/writeInt()/writeDouble()/writeFloat()随机访问文件44n随机访问文件(Random Access File)-实例随机访问文件RandomAccessFile rf=new RandomAccessFile(rtest.dat,rw);for(int i=0;i 10;i+)rf.writeDouble(i*1.414);rf.close();rf=new RandomAccessFile(rtest.dat,rw);rf.seek(5*8);rf.writeDouble(47.0001);rf.close();rf=new RandomAccessFile(rtest.dat,r);for(int i=0;i 10;i+)System.out.println(Value +i+:+rf.readDouble();rf.close();运行结果:Value 0:0.0Value 1:1.414Value 2:2.828Value 3:4.242Value 4:5.656Value 5:47.0001Value 6:8.484Value 7:9.898Value 8:11.312Value 9:12.72599999999999945n文件属性n读和写的权限n文件长度n修改时间n是否是目录njava.io.File类n设定文件属性n查询文件属性文件属性46文件属性n获取文件路径import java.io.*;class AttrDemo1 public static void main(String args)throws IOException File testfile=new File(.+File.separatorChar+test.txt);testfile.createNewFile();System.out.println(name=+testfile.getName();System.out.println(path=+testfile.getPath();System.out.println(absolute path=+testfile.getAbsolutePath();System.out.println(canonical path=+testfile.getCanonicalPath();java.io.File类npublic static final char separatorCharnUNIX系统为/,WINDOWS系统为D:javajava AttrDemo1name=test.txtpath=.test.txtabsolute path=D:java.test.txtcanonical path=D:javatest.txt47文件属性n获取文件修改时间import java.io.*;import java.util.Date;public class AttrDemo2 public static void main(String args)throws IOException File testfile=new File(test.txt);testfile.delete();testfile.createNewFile();long modtime=testfile.lastModified();System.out.println(last modification time#1=+new Date(modtime);testfile.setLastModified(0);modtime=testfile.lastModified();System.out.println(last modification time#2=+new Date(modtime);D:javajava AttrDemo2last modification time#1=Wed Mar 17 10:33:11 CST 2004last modification time#2=Thu Jan 01 08:00:00 CST 197048文件属性n获取和设定文件长度import java.io.*;public class AttrDemo3 public static void main(String args)th