1、1Java技术基础2第八章 输入输出1.概念2.Java I/O类3.Java I/O操作n标准输入/输出n文件读写操作n目录管理n随机访问文件n文件属性3概念nI/O来源n控制台(console,如DOS窗口)打印/读入n文件(file)读/写n网络接口(TCP/UDP端口)读/写n针对数据的读写n以流(stream)的方式对数据进行操作数据源程序读出数 据流目的程序写入数 据流流的重要特性n顺序读/写nsequentially4概念n读/写流的一般流程n读(Reading)1.open a stream /打开读出流2.while more information /判断3.read in
2、formation /读4.close the stream /关闭流n写(Writing)1.open a stream /打开写入流2.while more information /判断3.write information /写4.close the stream /关闭流5概念n两种流的定义(读取信息的基本数据单位)n字节流(byte stream):一个字节(8-bit)一个字节读/写n字符流(character stream):一个字符一个字符读/写(具有特定字符编码的数据)j a v a 语 言6A 61 76 61 D3 EF D1 D4以字节流的方式读:读8次,8个字节以字
3、符流的方式读:读6次,6个字符6第八章 文件输入输出1.概念2.Java I/O类3.Java I/O操作n标准输入/输出n文件读写操作n目录管理n随机访问文件n文件属性7Java 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 abstra
4、ct void write(int b)2.public void write(byte b)3.public void write(byte b,int offset,int length)n所有的读/写函数都抛出java.io.IOException8Java I/O类n字符流的读/写操作(来自JDK1.1)njava.io.Reader(抽象类)1.public int read()2.public int read(char cbuf)3.public abstract int read(char cbuf,int offset,int length)4.到达流的终点,无数据读出则返回
5、-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.IOException9Java I/O类nI/O流的层次关系nclass java.io.InputStream的子类nclass java.io.ByteArrayInputStreamnclass java.io.FileInputStreamnclass java.io.FilterInpu
6、tStreamnclass java.io.BufferedInputStreamnclass java.io.DataInputStream nclass java.io.ObjectInputStream nclass java.io.PipedInputStreamnclass java.io.SequenceInputStream 10Java I/O类nI/O流的层次关系nclass java.io.OutputStream的子类nclass java.io.ByteArrayOutputStreamnclass java.io.FileOutputStreamnclass java
7、.io.FilterOutputStreamnclass java.io.BufferedOutputStreamnclass java.io.DataOutputStream nclass java.io.PrintStreamnclass java.io.ObjectOutputStreamnclass java.io.PipedOutputStreamn 11Java I/O类nI/O流的层次关系nclass java.io.Reader的子类nclass java.io.BufferedReadernclass java.io.CharArrayReadernclass java.io
8、.FilterReader nclass java.io.InputStreamReadernclass java.io.FileReadernclass java.io.PipedReadernclass java.io.StringReadern 12Java I/O类nI/O流的层次关系nclass java.io.Writer的子类nclass java.io.BufferedWriternclass java.io.CharArrayWriternclass java.io.FilterWriternclass java.io.OutputStreamWriter nclass ja
9、va.io.FileWriternclass java.io.PipedWriternclass java.io.PrintWriternclass java.io.StringWritern 13Java I/O类nI/O流的分类(12个功能类)I/O类型所用到的类描述文件FileReader/FileWriterFileInputStream/FileOutputStream文件流(读/写文件)缓冲BufferedReader/BufferedWriterBufferedInputStreamBufferedOutputStream提高读/写效率打印PrintWriter PrintStr
10、eam(System.out.println()内存CharArrayReader/CharArrayWriterByteArrayInputStreamByteArrayOutputStreamStringReader/StringWriterStringBufferInputStream读/写内存14Java I/O类nI/O流的分类(12个功能类)I/O类型所用到的类描述字节流和字符流的转换InputStreamReaderOutputStreamWriter将InputStream中读入的字节转为字符/将字符转为字节写入OutputStream管道pipePipedReader/Pip
11、edWriterPipedInputStream/PipedOutputStream程序、进程通讯连接ConcatenationSequenceInputStream多个输入流连接为一个输入流对象串行化ObjectInputStreamObjectOutputStreamObject Serialization15Java I/O类nI/O流的分类(12个功能类)I/O类型所用到的类描述基本数据转化DataInputStreamDataOutputStreamJAVA基本数据类型的读/写计数LineNumberReaderLineNumberInputStream读操作时记录行数Peeking
12、 AheadPushbackReaderPushbackInputStream可回退缓存(pushback buffer)过滤FilterReader/FilterWriterFilterInputStream/FilterOutputStream在读/写操作时对数据进行过滤16第八章 文件输入输出1.概念2.Java I/O类3.Java I/O操作n标准输入/输出n文件读写操作n目录管理n随机访问文件n文件属性17Java I/O操作n主要内容1.标准输入/输出n控制台屏幕打印和键盘读入2.文件I/O操作n文件读写n如何提高文件读写效率n流的包装(Wrap)n基本数据转换流n目录管理n随机
13、访问文件(Random Access File)n文件属性3.网络流操作18n输出:控制台屏幕打印class Test public static void main(String args)System.out.println(“Hello World!”);标准输入/输出19n输入:键盘读入import java.io.IOException;class Test public static void main(String args)throws IOException byte b=new byte10;System.out.println(Received number=+Syste
14、m.in.read(b);标准输入/输出C:java TestAReceived number=3C:20n文件读/写流程1.打开文件流2.条件判断3.读出/写入4.关闭文件流n两种类型文件nFileInputStream/FileOutputStream(字节流)nFileReader/FileWriter (字符流)文件读写操作211.字节流构造方法npublic FileInputStream(File file)throws FileNotFoundExceptionnpublic FileInputStream(String name)throws FileNotFoundExcep
15、tionnpublic File(String pathname)npublic FileOutputStream(File file)throws FileNotFoundExceptionnpublic FileOutputStream(File file,boolean append)throws FileNotFoundException /是否向已存在的文件后添加npublic FileOutputStream(String name)throws FileNotFoundExceptionnpublic FileOutputStream(String name,boolean ap
16、pend)throws FileNotFoundException文件读写操作22n文件读写-实例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 ou
17、t =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);FileOutputSt
18、ream 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 IOException232.字符流构造方法npublic FileReader(File file)throws FileNotFoundExceptionnpublic FileReader(String fileName)throws Fil
19、eNotFoundExceptionnpublic File(String pathname)npublic FileWriter(File file)throws IOExceptionnpublic FileWriter(File file,boolean append)throws IOExceptionnpublic FileWriter(String fileName)throws IOExceptionnpublic FileWriter(String fileName,boolean append)throws IOException文件读写操作24n文件读写-实例2文件读写操作
20、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.clos
21、e();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 wri
22、te(char cbuf)throws IOExceptionpublic void write(char cbuf,int off,int len)throws IOException25n两类缓冲流n针对字节流njava.io.BufferedInputStream类njava.io.BufferedOutputStream类n针对字符流njava.io.BufferedReader类njava.io.BufferedWriter类如何提高文件读写效率26n构造方法npublic BufferedInputStream(InputStream in)2048 bytesnpublic Bu
23、fferedInputStream(InputStream in,int size)npublic BufferedOutputStream(OutputStream out)512 bytesnpublic BufferedOutputStream(OutputStream out,int size)npublic BufferedReader(Reader in)8192 bytesnpublic BufferedReader(Reader in,int sz)npublic BufferedWriter(Writer out)8192 bytenpublic BufferedWriter
24、(Writer out,int sz)如何提高文件读写效率27 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如何提高文件读写效率 String filename =“test.txt”;FileInputStream fis =new FileInputStream(f
25、ilename);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);FileInputStream fis=new FileInputStream(“test.txt”);int count=0;final int BUFSIZE=1024;byte buf=new byteBUFSIZE;int len;while(len=fis.read(buf)!=
26、-1)for(int i=0;i len;i+)if(bufi=A)count+;fis.close();28 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如何提高文件读写效率29n概述流的包装(wrap)FileReader fr
27、 =new FileReader(filename);BufferedReader br=new BufferedReader(fr);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.Pri
28、ntWritern利用不同流的特点(方法)n寻找合适的方法完成特定的需求n对已有的流进行再处理30n流的种类n节点流n直接对数据源进行读/写操作的流n处理流n对一个已有的流进行某种操作的流流的包装(wrap)31n节点流nFileInputStream,PipedInputStream,ByteArrayInputStream,StringBufferInputStreamnFileOutputStream,PipedOutputStream,ByteArrayOutputStreamnCharArrayReader,FileReader,PipedReader,StringReadernCh
29、arArrayWriter,FileWriter,PipedWriter,StringWriter流的包装(wrap)32n处理流nFilterOutputStream,DataOutputStream,BufferedOutputStream,PrintStreamnFilterInputStream,DataInputStream,BufferedInputStream,nBufferedReader,InputStreamReader,FilterReadernBufferedWriter,OutputStreamReader,FilterWriter,PrintWriter流的包装(w
30、rap)33n一个实例njava.io.FileReadernpublic FileReader(File file)throws FileNotFoundExceptionnpublic FileReader(String fileName)throws FileNotFoundExceptionnjava.io.BufferedReadernpublic BufferedReader(Reader in)8192 bytesnpublic BufferedReader(Reader in,int sz)n流的包装改变了流的行为流的包装(wrap)34n流的包装(wrap)-实例1流的包装(
31、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 InputStrea
32、mReader(InputStream in)public BufferedReader(Reader in)35n概述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(Outpu
33、tStream 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)基本数据转换流36DataOutputStream out=new DataOutputStream(new FileOutputStream(invoice1.txt);double prices=19.99,9.99;int units=12,8;String descs=Jav
34、a 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基本数据转换流-实例基本数据转换流DataInputStream in=new DataInputStream(new FileInputStream(invoice1.txt);double total;try while(true
35、)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(Youve ordered +unit+units of +desc+at$+price);total=total+unit*price;catch(EOFException e)System.out.println(
36、For a TOTAL of:$+total);in.close();19.99 12 Java T-shirt9.99 8 Java Mug 37n概述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.co
37、nf”、“inetd.conf”nWindows平台,绝对路径名的前缀由“盘符:”组成;UNC 路径名前缀为“”,然后是主机名和共享名,相对路径名无盘符,例“c:windowsnotepad.exe”、“notepad.exe”目录管理38n方法npublic boolean canWrite()/canRead()npublic boolean exists()npublic boolean delete()删除文件或目录,若删除目录,要求该目录必须为空npublic boolean createNewFile()创建一个空文件,当且仅当该文件不存在npublic boolean isDir
38、ectory()/isFile()/isHidden()npublic long lastModified()/public boolean setLastModified(long time)npublic String list()得到当前目录下的所有文件名和目录名,若该File对象不是表示目录,则返回nullnpublic boolean mkdir()/mkdirs()创建一个目录npublic boolean renameTo(File dest)npublic boolean setReadOnly()目录管理39n目录管理方法举例目录管理import java.io.File;p
39、ublic 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);40n目录管理方法举例目录管理import java.io.File;import java.io.FilenameFilter;public class DirList public static void main(String args)File path=new File(.)
40、;String list=path.list(new DirFilter(args0);for(int i=0;i list.length;i+)System.out.println(listi);class DirFilter implements FilenameFilter String key;DirFilter(String key)this.key=key;public boolean accept(File dir,String name)String f=new File(name).getName();return f.indexOf(key)!=-1;java.util.F
41、ilenameFilter 接口 public boolean accept(File dir,String name);/是否指定的文件应包含在文件列表中public String getName()in java.io.File/获得文件或目录名,仅仅是最后的部分41n随机访问文件(Random Access File)njava.io.RandomAccessFile类n读写操作在同一个类中完成,须在构造对象时指定参数n通过移动文件指针(file pointer)在文件的指定位置进行读写操作n构造方法npublic RandomAccessFile(String name,String
42、mode)throws FileNotFoundExceptionnpublic RandomAccessFile(File file,String mode)throws FileNotFoundExceptionnmode:“r”,“rw”随机访问文件42n方法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()/
43、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()随机访问文件43n随机访问文件(Random
44、 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
45、+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.72599999999999944n文件的特性n读和写的权限n文件长度n修改时间n是否是目录njava.io.File类n设定文件属性n查询文件属性文件属性45文件属性n获取文件路径import java.io.*;class AttrDemo1 public sta
46、tic void main(String args)throws IOException File testfile=new File(.+File.separatorChar+testfile1);testfile.createNewFile();System.out.println(name=+testfile.getName();System.out.println(path=+testfile.getPath();System.out.println(absolute path=+testfile.getAbsolutePath();System.out.println(canonic
47、al path=+testfile.getCanonicalPath();46文件属性n获取文件修改时间import java.io.*;import java.util.*;public class AttrDemo2 public static void main(String args)throws IOException File testfile=new File(testfile2);testfile.delete();testfile.createNewFile();long modtime=testfile.lastModified();System.out.println(l
48、ast modification time#1=+new Date(modtime);testfile.setLastModified(0);modtime=testfile.lastModified();System.out.println(last modification time#2=+new Date(modtime);47文件属性n获取和设定文件长度import java.io.*;public class AttrDemo3 public static void main(String args)throws IOException File testfile=new File(
49、testfile3);testfile.delete();testfile.createNewFile();System.out.println(length#1=+testfile.length();RandomAccessFile raf=new RandomAccessFile(testfile3,rw);raf.setLength(100);raf.close();System.out.println(length#2=+testfile.length();48文件属性n设置读写权限import java.io.*;public class AttrDemo4 public stati
50、c void main(String args)throws IOException File testfile=new File(testfile4);testfile.delete();testfile.createNewFile();if(testfile.canRead()System.out.println(file can be read#1);if(testfile.canWrite()System.out.println(file can be written#1);testfile.setReadOnly();if(testfile.canRead()System.out.p