java IO 总结学习

代码:http://developer.51cto.com/art/201109/292225.htm


Java 流在处理上分为字符流和字节流。字符流处理的单元为 2 个字节的 Unicode 字符,分别操作字符、字符数组或字符串,而字节流处理单元为 1 个字节,操作字节和字节数组。 
Java 内用 Unicode 编码存储字符,字符流处理类负责将外部的其他编码的字符流和 java 内 Unicode 字符流之间的转换。而类 InputStreamReader  OutputStreamWriter 处理字符流和字节流的转换。字符流(一次可以处理一个缓冲区)一次操作比字节流(一次一个字节)效率高。 
 
( 一 )以字节为导向的 stream------InputStream/OutputStream 
InputStream 和 OutputStream 是两个 abstact 类,所以字节为导向的 stream 都扩展这两个基类。
1、 InputStream 
1.1 
ByteArrayInputStream -- 
把内存中的一个缓冲区作为 InputStream 使用 . 
construct--- 
(A)ByteArrayInputStream(byte[]) 
创建一个新字节数组输入流( ByteArrayInputStream ),它从指定字节数组中读取数据( 使用 byte 作为其缓冲区数组) 
(B)---ByteArrayInputStream(byte[], int, int) 创建一个新字节数组输入流,它从指定字节数组中读取数据。 
---mark:: 该字节数组未被复制。 
1.2 
StringBufferInputStream -- 
把一个 String 对象作为 InputStream . 
construct---  
StringBufferInputStream(String) 据指定串创建一个读取数据的输入流串。 
 
注释:不推荐使用 StringBufferInputStream 方法。 此类不能将字符正确的转换为字节。 
同 JDK 1.1 版中的类似,从一个串创建一个流的最佳方法是采用 StringReader 类。 
1.3 
FileInputStream -- 把一个文件作为 InputStream ,实现对文件的读取操作 
construct--- 
(A)FileInputStream(File name) 创建一个输入文件流,从指定的 File 对象读取数据。 
(B)FileInputStream(FileDescriptor) 
创建一个输入文件流,从指定的文件描述器读取数据。 
(C)-FileInputStream(String  name) 创建一个输入文件流,从指定名称的文件读取数据。 
method ---- read() 从当前输入流中读取一字节数据。 
read(byte[]) 
将当前输入流中 b.length 个字节数据读到一个字节数组中。 
read(byte[], int, int) 将输入流中 len 个字节数据读入一个字节数组中。 
1.4
PipedInputStream :实现了 pipe 的概念,主要在线程中使用 . 管道输入流是指一个通讯管道的接收端。 
一个线程通过管道输出流发送数据,而另一个线程通过管道输入流读取数据,这样可实现两个线程间的通讯。 
construct--- 
PipedInputStream() 创建一个管道输入流,它还未与一个管道输出流连接。 
PipedInputStream(PipedOutputStream) 创建一个管道输入流 , 它已连接到一个管道输出流。 
1.5 
SequenceInputStream :把多个 InputStream 合并为一个 InputStream . “序列输入流”类允许应用程序把几个输入流连续地合并起来, 
并且使它们像单个输入流一样出现。每个输入流依次被读取,直到到达该流的末尾。 
然后“序列输入流”类关闭这个流并自动地切换到下一个输入流。 
construct--- 
SequenceInputStream(Enumeration) 创建一个新的序列输入流,并用指定的输入流的枚举值初始化它。 
SequenceInputStream(InputStream, InputStream) 创建一个新的序列输入流,初始化为首先 读输入流 s1, 然后读输入流 s2 。 
 
2、 OutputSteam 
2.1 
ByteArrayOutputStream : 把信息存入内存中的一个缓冲区中 . 该类实现一个以字节数组形式写入数据的输出流。 
当数据写入缓冲区时,它自动扩大。用 toByteArray() 和 toString() 能检索数据。 
constructor 
(A)--- ByteArrayOutputStream() 创建一个新的字节数组输出流。 
(B)--- ByteArrayOutputStream() 创建一个新的字节数组输出流。 
(C)--- ByteArrayOutputStream(int) 创建一个新的字节数组输出流,并带有指定大小字节的缓冲区容量。 
toString(String) 根据指定字符编码将缓冲区内容转换为字符串,并将字节转换为字符。 
write(byte[], int, int) 将指定字节数组中从偏移量 off 开始的 len 个字节写入该字节数组输出流。 
write(int) 将指定字节写入该字节数组输出流。 
writeTo(OutputStream) 用 out.write(buf, 0, count) 调用输出流的写方法将该字节数组输出流的全部内容写入指定的输出流参数。 
2.2  
FileOutputStream: 文件输出流是向 File 或 FileDescriptor 输出数据的一个输出流。 
constructor 
(A)FileOutputStream(File  name) 创建一个文件输出流,向指定的 File 对象输出数据。 
(B)FileOutputStream(FileDescriptor) 创建一个文件输出流,向指定的文件描述器输出数据。 
(C)FileOutputStream(String  name) 创建一个文件输出流,向指定名称的文件输出数据。 
(D)FileOutputStream(String, boolean) 用指定系统的文件名,创建一个输出文件。 
2.3 
PipedOutputStream: 管道输出流是指一个通讯管道的发送端。 一个线程通过管道输出流发送数据, 
而另一个线程通过管道输入流读取数据,这样可实现两个线程间的通讯。 
constructor 
(A)PipedOutputStream() 创建一个管道输出流,它还未与一个管道输入流连接。 
(B)PipedOutputStream(PipedInputStream) 创建一个管道输出流,它已连接到一个管道输入流。 
 
( 二 )以字符为导向的 stream Reader/Writer 
以 Unicode 字符为导向的 stream ,表示以 Unicode 字符为单位从 stream 中读取或往 stream 中写入信息。 
Reader/Writer 为 abstact 类 
以 Unicode 字符为导向的 stream 包括下面几种类型: 
1. Reader 
1.1 
CharArrayReader :与 ByteArrayInputStream 对应此类实现一个可用作字符输入流的字符缓冲区 
constructor 
CharArrayReader(char[]) 用指定字符数组创建一个 CharArrayReader 。 
CharArrayReader(char[], int, int) 用指定字符数组创建一个 CharArrayReader 
1.2 
StringReader : 与 StringBufferInputStream 对应其源为一个字符串的字符流。 
StringReader(String) 创建一新的串读取者。
1.3 
FileReader : 与 FileInputStream 对应 
1.4 
PipedReader :与 PipedInputStream 对应 
 
2.  Writer   
2.1    CharArrayWrite : 与 ByteArrayOutputStream 对应 
2.2   StringWrite :无与之对应的以字节为导向的 stream 
2.3  FileWrite : 与 FileOutputStream 对应 
2.4  PipedWrite :与 PipedOutputStream 对应 
 
3、两种不同导向的 stream 之间的转换  
3.1 
InputStreamReader 和 OutputStreamReader : 
把一个以字节为导向的 stream 转换成一个以字符为导向的 stream 。 
InputStreamReader 类是从字节流到字符流的桥梁:它读入字节,并根据指定的编码方式,将之转换为字符流。 
使用的编码方式可能由名称指定,或平台可接受的缺省编码方式。 
InputStreamReader 的 read() 方法之一的每次调用,可能促使从基本字节输入流中读取一个或多个字节。 
为了达到更高效率,考虑用 BufferedReader 封装 InputStreamReader , 
BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); 

 

InputStreamReader(InputStream) 用缺省的字符编码方式,创建一个 InputStreamReader 。 
InputStreamReader(InputStream, String) 用已命名的字符编码方式,创建一个 InputStreamReader 。 
 
OutputStreamWriter 将多个字符写入到一个输出流,根据指定的字符编码将多个字符转换为字节。 
每个 OutputStreamWriter 合并它自己的 CharToByteConverter, 因而是从字符流到字节流的桥梁。
 
(三)Java IO 的一般使用原则 :  
一、按数据来源(去向)分类: 
、是文件: FileInputStream, FileOutputStream, ( 字节流 )FileReader, FileWriter( 字符 ) 
、是 byte[]  ByteArrayInputStream, ByteArrayOutputStream( 字节流 ) 
、是 Char[]: CharArrayReader, CharArrayWriter( 字符流 ) 
4 、是 String: StringBufferInputStream, StringBufferOuputStream ( 字节流 )StringReader, StringWriter( 字符流 )
5 、网络数据流: InputStream, OutputStream,( 字节流 ) Reader, Writer( 字符流 ) 
二、按是否格式化输出分: 
1 、要格式化输出: PrintStream, PrintWriter 
三、按是否要缓冲分: 
1 、要缓冲: BufferedInputStream, BufferedOutputStream,( 字节流 ) BufferedReader, BufferedWriter( 字符流 ) 
四、按数据格式分: 
、二进制格式(只要不能确定是纯文本的) : InputStream, OutputStream 及其所有带 Stream 结束的子类 
纯文本格式(含纯英文与汉字或其他编码方式) Reader, Writer 及其所有带 Reader, Writer 的子类 
五、按输入输出分: 
1 、输入: Reader, InputStream 类型的子类 
2 、输出: Writer, OutputStream 类型的子类 
六、特殊需要: 
1 、从 Stream 到 Reader,Writer 的转换类: InputStreamReader, OutputStreamWriter 
、对象输入输出: ObjectInputStream, ObjectOutputStream 
、进程间通信: PipeInputStream, PipeOutputStream, PipeReader, PipeWriter 
、合并输入: SequenceInputStream 
5 、更特殊的需要: PushbackInputStream, PushbackReader, LineNumberInputStream, LineNumberReader
决定使用哪个类以及它的构造进程的一般准则如下(不考虑特殊需要): 
首先,考虑最原始的数据格式是什么: 原则四 
第二,是输入还是输出:原则五 
第三,是否需要转换流:原则六第 1 点 
第四,数据来源(去向)是什么:原则一 
第五,是否要缓冲:原则三 (特别注明:一定要注意的是 readLine() 是否有定义,有什么比 read, write 更特殊的输入或输出方法


总结一下Java I/O文件读写基本类相关知识和概念,对于程序设计者来说,创建一个好的输入/输出系统是一项艰难的任务,其中挑战来源于所有的可能性,不仅存在各种源端与接收端(文件,控制台,网络链接等),而且还需要以各种不同的方式与它们通信(顺序,随机存取,缓冲,二进制,按字符,按行,按字等)。

 

Java I/O主要包括如下几个层次:

1. File(文件特征与管理):用于文件或者目录的描述信息,例如生成新目录,修改文件名,删除文件,判断文件所在路径等。

2. InputStream(二进制格式操作):抽象类,基于字节的输入操作,是所有输入流的父类。定义了所有输入流都具有的共同特征。

3. OutputStream(二进制格式操作):抽象类。基于字节的输出操作。是所有输出流的父类。定义了所有输出流都具有的共同特征。

 

Java中字符是采用Unicode标准,一个字符是16位,即一个字符使用两个字节来表示。为此,JAVA中引入了处理字符的流。

4. Reader(文件格式操作):抽象类,基于字符的输入操作。

5. Writer(文件格式操作):抽象类,基于字符的输出操作。

6. RandomAccessFile(随机文件操作):它的功能丰富,可以从文件的任意位置进行存取(输入输出)操作

 

1. File

它是独立于系统平台的,利用其构造函数创建出相应的File 对象;再调用其中的方法实现对文件的各个属性方面的操作。

构造函数:
File( String  path)
File(String path, String FileName)
File(File dir, String name)

 

用途:File类提供了一种与机器无关的方式来描述一个文件对象的属性,通过类File所提供的方法,可以得到文件或目录的描述信息,这主要包括名称、所在路经、可读性、可写性、文件的长度等,还可以生成新的目录、改变文件名、删除文件、列出一个目录中所有的文件等。 

Java代码   收藏代码
  1. public static void main(String[] args) throws IOException {  
  2.         File f = new File("dir");  
  3.   
  4.         f.createNewFile();// 创建一个.txt这个文件  
  5.   
  6.         f.mkdir();// 创建一个名为.txt的目录  
  7.   
  8.         /* 
  9.          * 使用绝对路径 
  10.          *  
  11.          * File f=new File("D:\\dir\\src\\A.java"); 
  12.          *  
  13.          * f.createNewFile(); 
  14.          */  
  15.   
  16.         /* 
  17.          * 跨平台使用 
  18.          *  
  19.          * 根据不同操作系统获得对应的分隔符 File fDir=new File(File.separator); 
  20.          *  
  21.          * String strFile="dir"+File.separator+"src"+File.separator +"A.java"; 
  22.          *  
  23.          * File f=new File(fDir,strFile); 
  24.          *  
  25.          * f.createNewFile(); 
  26.          *  
  27.          * f.delete();//删除文件或目录 
  28.          *  
  29.          * //f.deleteOnExit(); 
  30.          */  
  31.   
  32.         /* 
  33.          * 在缺省的临时文件目录下创建临时文件 
  34.          *  
  35.          * for(int i=0;i<5;i++) 
  36.          *  
  37.          * { 
  38.          *  
  39.          * File f=File.createTempFile("winTemp",".tmp"); 
  40.          *  
  41.          * f.deleteOnExit();//退出时删除 
  42.          *  
  43.          *  
  44.          *  
  45.          * } 
  46.          */  
  47.   
  48.         /*  
  49.          * 列出指定目录下所有子目录及文件的名称  
  50.          */  
  51.         File fDir = new File(File.separator);  
  52.         String strFile = "dir" + File.separator + "src";  
  53.         File f = new File(fDir, strFile);  
  54.         String[] names = f.list();  
  55.         for (int i = 0; i < names.length; i++) {  
  56.             System.out.println(names[i]);  
  57.         }  
  58.   
  59.         // 有过滤器的情况FilenameFilter是个接口  
  60.         File dir = new File(File.separator);  
  61.   
  62.         String filepath = "dir" + File.separator + "src";  
  63.   
  64.         /** 
  65.          * dir 
  66.          * 上级抽象路径,如果dir为null,那么程序将自动调用单个参数的File构造方法,同时将filepath路径应用到File但构造参数 
  67.          * 如果dir为//,则此路径为本文件所在磁盘根目录 
  68.          */  
  69.         File f = new File(dir, filepath);  
  70.         if (f.exists()) {  
  71.         } else {  
  72.             f.mkdirs();  
  73.         }  
  74.   
  75.         String[] names = f.list(new FilenameFilter() { // 实现了FilenameFilter接口的匿名类,实现accept方法过滤文件  
  76.   
  77.                     @Override  
  78.                     public boolean accept(File dir, String name) {  
  79.                         System.out.println(name.indexOf(".java"));  
  80.                         return name.indexOf(".java") != -1;  
  81.                     }  
  82.                 });  
  83.   
  84.         for (int i = 0; i < names.length; i++) {  
  85.             System.out.println(names[i]);  
  86.         }  
  87.     }  
[java]  view plain copy
  1. public static void main(String[] args) throws IOException {  
  2.         File f = new File("dir");  
  3.   
  4.         f.createNewFile();// 创建一个.txt这个文件   
  5.   
  6.         f.mkdir();// 创建一个名为.txt的目录   
  7.   
  8.         /* 
  9.          * 使用绝对路径 
  10.          *  
  11.          * File f=new File("D:\\dir\\src\\A.java"); 
  12.          *  
  13.          * f.createNewFile(); 
  14.          */  
  15.   
  16.         /* 
  17.          * 跨平台使用 
  18.          *  
  19.          * 根据不同操作系统获得对应的分隔符 File fDir=new File(File.separator); 
  20.          *  
  21.          * String strFile="dir"+File.separator+"src"+File.separator +"A.java"; 
  22.          *  
  23.          * File f=new File(fDir,strFile); 
  24.          *  
  25.          * f.createNewFile(); 
  26.          *  
  27.          * f.delete();//删除文件或目录 
  28.          *  
  29.          * //f.deleteOnExit(); 
  30.          */  
  31.   
  32.         /* 
  33.          * 在缺省的临时文件目录下创建临时文件 
  34.          *  
  35.          * for(int i=0;i<5;i++) 
  36.          *  
  37.          * { 
  38.          *  
  39.          * File f=File.createTempFile("winTemp",".tmp"); 
  40.          *  
  41.          * f.deleteOnExit();//退出时删除 
  42.          *  
  43.          *  
  44.          *  
  45.          * } 
  46.          */  
  47.   
  48.         /* 
  49.          * 列出指定目录下所有子目录及文件的名称 
  50.          */  
  51.         File fDir = new File(File.separator);  
  52.         String strFile = "dir" + File.separator + "src";  
  53.         File f = new File(fDir, strFile);  
  54.         String[] names = f.list();  
  55.         for (int i = 0; i < names.length; i++) {  
  56.             System.out.println(names[i]);  
  57.         }  
  58.   
  59.         // 有过滤器的情况FilenameFilter是个接口   
  60.         File dir = new File(File.separator);  
  61.   
  62.         String filepath = "dir" + File.separator + "src";  
  63.   
  64.         /** 
  65.          * dir 
  66.          * 上级抽象路径,如果dir为null,那么程序将自动调用单个参数的File构造方法,同时将filepath路径应用到File但构造参数 
  67.          * 如果dir为//,则此路径为本文件所在磁盘根目录 
  68.          */  
  69.         File f = new File(dir, filepath);  
  70.         if (f.exists()) {  
  71.         } else {  
  72.             f.mkdirs();  
  73.         }  
  74.   
  75.         String[] names = f.list(new FilenameFilter() { // 实现了FilenameFilter接口的匿名类,实现accept方法过滤文件   
  76.   
  77.                     @Override  
  78.                     public boolean accept(File dir, String name) {  
  79.                         System.out.println(name.indexOf(".java"));  
  80.                         return name.indexOf(".java") != -1;  
  81.                     }  
  82.                 });  
  83.   
  84.         for (int i = 0; i < names.length; i++) {  
  85.             System.out.println(names[i]);  
  86.         }  
  87.     }  
[java]  view plain copy
  1. public static void main(String[] args) throws IOException {  
  2.         File f = new File("dir");  
  3.   
  4.         f.createNewFile();// 创建一个.txt这个文件  
  5.   
  6.         f.mkdir();// 创建一个名为.txt的目录  
  7.   
  8.         /* 
  9.          * 使用绝对路径 
  10.          *  
  11.          * File f=new File("D:\\dir\\src\\A.java"); 
  12.          *  
  13.          * f.createNewFile(); 
  14.          */  
  15.   
  16.         /* 
  17.          * 跨平台使用 
  18.          *  
  19.          * 根据不同操作系统获得对应的分隔符 File fDir=new File(File.separator); 
  20.          *  
  21.          * String strFile="dir"+File.separator+"src"+File.separator +"A.java"; 
  22.          *  
  23.          * File f=new File(fDir,strFile); 
  24.          *  
  25.          * f.createNewFile(); 
  26.          *  
  27.          * f.delete();//删除文件或目录 
  28.          *  
  29.          * //f.deleteOnExit(); 
  30.          */  
  31.   
  32.         /* 
  33.          * 在缺省的临时文件目录下创建临时文件 
  34.          *  
  35.          * for(int i=0;i<5;i++) 
  36.          *  
  37.          * { 
  38.          *  
  39.          * File f=File.createTempFile("winTemp",".tmp"); 
  40.          *  
  41.          * f.deleteOnExit();//退出时删除 
  42.          *  
  43.          *  
  44.          *  
  45.          * } 
  46.          */  
  47.   
  48.         /* 
  49.          * 列出指定目录下所有子目录及文件的名称 
  50.          */  
  51.         File fDir = new File(File.separator);  
  52.         String strFile = "dir" + File.separator + "src";  
  53.         File f = new File(fDir, strFile);  
  54.         String[] names = f.list();  
  55.         for (int i = 0; i < names.length; i++) {  
  56.             System.out.println(names[i]);  
  57.         }  
  58.   
  59.         // 有过滤器的情况FilenameFilter是个接口  
  60.         File dir = new File(File.separator);  
  61.   
  62.         String filepath = "dir" + File.separator + "src";  
  63.   
  64.         /** 
  65.          * dir 
  66.          * 上级抽象路径,如果dir为null,那么程序将自动调用单个参数的File构造方法,同时将filepath路径应用到File但构造参数 
  67.          * 如果dir为//,则此路径为本文件所在磁盘根目录 
  68.          */  
  69.         File f = new File(dir, filepath);  
  70.         if (f.exists()) {  
  71.         } else {  
  72.             f.mkdirs();  
  73.         }  
  74.   
  75.         String[] names = f.list(new FilenameFilter() { // 实现了FilenameFilter接口的匿名类,实现accept方法过滤文件  
  76.   
  77.                     @Override  
  78.                     public boolean accept(File dir, String name) {  
  79.                         System.out.println(name.indexOf(".java"));  
  80.                         return name.indexOf(".java") != -1;  
  81.                     }  
  82.                 });  
  83.   
  84.         for (int i = 0; i < names.length; i++) {  
  85.             System.out.println(names[i]);  
  86.         }  
  87.     }  

 

2. InputStream/OutputStream(抽象基类)

(1) 它们主要提供文件内容操作的基本功能函数read()、 write()、close()等;一般都是创建出其派生类对象(完成指定的特殊功能)来实现文件读写。
(2)文件操作的一般方法:
根据所要操作的类型生成对应输入输出文件类的对象;
调用此类的成员函数实现文件数据的读写;
关闭此文件流对象。 
(3)文件操作的应用要点:
异常的捕获:由于包java.io中几乎所有的类都声明有I/O异常,因此程序应该对这些异常加以处理。
流结束的判断:方法read()的返回值为-1时;readLine()的返回值为null时。

 

上边两个抽象基类实现类有FileInputStream/FileOutputStream(本地文件读写类):它们用于本地文件的二进制格式顺序读写。

 

java.io.FileInputStream是InputStream的子类。从开头File名称上就可以知道,FileInputStream与从指定的文件中读取数据至目的地有关。而java.io.FileOutputStream是 OutputStream的子类,顾名思义,FileOutputStream主要与从来源地写入数据至指定的文件中有关。

 

当建立一个FileInputStream或FileOutputStream的实例时,必须指定文件位置及文件名称,实例被建立时文件的流就会开启;而不使用流时,必须关闭文件流,以释放与流相依的系统资源,完成文件读/写的动作。

 

FileInputStream可以使用read()方法一次读入一个字节,并以int类型返回,或者是使用read()方法时读入至一个byte 数组,byte数组的元素有多少个,就读入多少个字节。在将整个文件读取完成或写入完毕的过程中,这么一个byte数组通常被当作缓冲区,因为这么一个 byte数组通常扮演承接数据的中间角色。

Java代码   收藏代码
  1. public class FileStreamDemo {  
  2.       
  3.     public static void main(String[] args) {  
  4.           
  5.         try {  
  6.               
  7.             byte[] buffer = new byte[1024];  
  8.               
  9.             // 来源文件  
  10.             FileInputStream fileInputStream = new FileInputStream(new File(args[0]));  
  11.               
  12.             // 目的文件  
  13.             FileOutputStream fileOutputStream = new FileOutputStream(new File(args[1]));  
  14.               
  15.             // available()可取得未读取的数据长度  
  16.             System.out.println("复制文件:" + fileInputStream.available() + "字节");  
  17.   
  18.             while (true) {  
  19.                 if (fileInputStream.available() < 1024) {  
  20.                     // 剩余的数据比1024字节少  
  21.                     // 一位一位读出再写入目的文件  
  22.                     int remain = -1;  
  23.                     while ((remain = fileInputStream.read()) != -1) {  
  24.                         fileOutputStream.write(remain);  
  25.                     }  
  26.                     break;  
  27.                 } else {  
  28.                     // 从来源文件读取数据至缓冲区  
  29.                     fileInputStream.read(buffer);  
  30.                     // 将数组数据写入目的文件  
  31.                     fileOutputStream.write(buffer);  
  32.                 }  
  33.             }  
  34.   
  35.             // 关闭流  
  36.             fileInputStream.close();  
  37.             fileOutputStream.close();  
  38.   
  39.             System.out.println("复制完成");  
  40.         } catch (ArrayIndexOutOfBoundsException e) {  
  41.             System.out.println("using: java FileStreamDemo src des");  
  42.             e.printStackTrace();  
  43.         } catch (IOException e) {  
  44.             e.printStackTrace();  
  45.         }  
  46.     }  
  47. }  
[java]  view plain copy
  1. public class FileStreamDemo {  
  2.       
  3.     public static void main(String[] args) {  
  4.           
  5.         try {  
  6.               
  7.             byte[] buffer = new byte[1024];  
  8.               
  9.             // 来源文件   
  10.             FileInputStream fileInputStream = new FileInputStream(new File(args[0]));  
  11.               
  12.             // 目的文件   
  13.             FileOutputStream fileOutputStream = new FileOutputStream(new File(args[1]));  
  14.               
  15.             // available()可取得未读取的数据长度   
  16.             System.out.println("复制文件:" + fileInputStream.available() + "字节");  
  17.   
  18.             while (true) {  
  19.                 if (fileInputStream.available() < 1024) {  
  20.                     // 剩余的数据比1024字节少   
  21.                     // 一位一位读出再写入目的文件   
  22.                     int remain = -1;  
  23.                     while ((remain = fileInputStream.read()) != -1) {  
  24.                         fileOutputStream.write(remain);  
  25.                     }  
  26.                     break;  
  27.                 } else {  
  28.                     // 从来源文件读取数据至缓冲区   
  29.                     fileInputStream.read(buffer);  
  30.                     // 将数组数据写入目的文件   
  31.                     fileOutputStream.write(buffer);  
  32.                 }  
  33.             }  
  34.   
  35.             // 关闭流   
  36.             fileInputStream.close();  
  37.             fileOutputStream.close();  
  38.   
  39.             System.out.println("复制完成");  
  40.         } catch (ArrayIndexOutOfBoundsException e) {  
  41.             System.out.println("using: java FileStreamDemo src des");  
  42.             e.printStackTrace();  
  43.         } catch (IOException e) {  
  44.             e.printStackTrace();  
  45.         }  
  46.     }  
  47. }  
[java]  view plain copy
  1. public class FileStreamDemo {  
  2.       
  3.     public static void main(String[] args) {  
  4.           
  5.         try {  
  6.               
  7.             byte[] buffer = new byte[1024];  
  8.               
  9.             // 来源文件  
  10.             FileInputStream fileInputStream = new FileInputStream(new File(args[0]));  
  11.               
  12.             // 目的文件  
  13.             FileOutputStream fileOutputStream = new FileOutputStream(new File(args[1]));  
  14.               
  15.             // available()可取得未读取的数据长度  
  16.             System.out.println("复制文件:" + fileInputStream.available() + "字节");  
  17.   
  18.             while (true) {  
  19.                 if (fileInputStream.available() < 1024) {  
  20.                     // 剩余的数据比1024字节少  
  21.                     // 一位一位读出再写入目的文件  
  22.                     int remain = -1;  
  23.                     while ((remain = fileInputStream.read()) != -1) {  
  24.                         fileOutputStream.write(remain);  
  25.                     }  
  26.                     break;  
  27.                 } else {  
  28.                     // 从来源文件读取数据至缓冲区  
  29.                     fileInputStream.read(buffer);  
  30.                     // 将数组数据写入目的文件  
  31.                     fileOutputStream.write(buffer);  
  32.                 }  
  33.             }  
  34.   
  35.             // 关闭流  
  36.             fileInputStream.close();  
  37.             fileOutputStream.close();  
  38.   
  39.             System.out.println("复制完成");  
  40.         } catch (ArrayIndexOutOfBoundsException e) {  
  41.             System.out.println("using: java FileStreamDemo src des");  
  42.             e.printStackTrace();  
  43.         } catch (IOException e) {  
  44.             e.printStackTrace();  
  45.         }  
  46.     }  
  47. }  

 

 PipedInputStream/PipedOutputStream(管道输入输出)

(1)它用于实现管道的二进制格式的输入输出(将一个线程的输出结果直接连接到另一个线程的输入端口,实现两者数据直接传送)。
(2) PipedReader/PipedWriter类:它用于实现管道的字符格式的输入输出。
(3)要求:操作时需要将两个端口相互连结。
(4)实现原理:

  

(5) 管道的连接:
方法一:是通过构造函数直接将某一个程序的输出作为另一个程序的输入,在定义对象时指明目标管道对象

方法二:是利用双方类中的任一个成员函数 connect()相连接
(6)实例讲解: Sender.java, Receiver.java, PipedIO.java (使用PipedWriter,PipedReader)

Sender.java

Java代码   收藏代码
  1. import java.io.PipedWriter;  
  2. import java.util.Random;  
  3.   
  4. class Sender extends Thread {  
  5.     private Random rand = new Random();  
  6.     private PipedWriter out = new PipedWriter();  
  7.   
  8.     public PipedWriter getPipedWriter() {  
  9.         return out;  
  10.     }  
  11.   
  12.     public void run() {  
  13.         while (true) {  
  14.             for (char c = 'A'; c <= 'z'; c++) {  
  15.                 try {  
  16.                     out.write(c);  
  17.                     sleep(rand.nextInt(500));  
  18.                 } catch (Exception e) {  
  19.                     throw new RuntimeException(e);  
  20.                 }  
  21.             }  
  22.         }  
  23.     }  
  24. }  
[java]  view plain copy
  1. import java.io.PipedWriter;  
  2. import java.util.Random;  
  3.   
  4. class Sender extends Thread {  
  5.     private Random rand = new Random();  
  6.     private PipedWriter out = new PipedWriter();  
  7.   
  8.     public PipedWriter getPipedWriter() {  
  9.         return out;  
  10.     }  
  11.   
  12.     public void run() {  
  13.         while (true) {  
  14.             for (char c = 'A'; c <= 'z'; c++) {  
  15.                 try {  
  16.                     out.write(c);  
  17.                     sleep(rand.nextInt(500));  
  18.                 } catch (Exception e) {  
  19.                     throw new RuntimeException(e);  
  20.                 }  
  21.             }  
  22.         }  
  23.     }  
  24. }  
[java]  view plain copy
  1. import java.io.PipedWriter;  
  2. import java.util.Random;  
  3.   
  4. class Sender extends Thread {  
  5.     private Random rand = new Random();  
  6.     private PipedWriter out = new PipedWriter();  
  7.   
  8.     public PipedWriter getPipedWriter() {  
  9.         return out;  
  10.     }  
  11.   
  12.     public void run() {  
  13.         while (true) {  
  14.             for (char c = 'A'; c <= 'z'; c++) {  
  15.                 try {  
  16.                     out.write(c);  
  17.                     sleep(rand.nextInt(500));  
  18.                 } catch (Exception e) {  
  19.                     throw new RuntimeException(e);  
  20.                 }  
  21.             }  
  22.         }  
  23.     }  
  24. }  

 

 

Receiver.java

Java代码   收藏代码
  1. import java.io.IOException;  
  2. import java.io.PipedReader;  
  3.   
  4. class Receiver extends Thread {  
  5.     private PipedReader in;  
  6.   
  7.     public Receiver(Sender sender) throws IOException {  
  8.         in = new PipedReader(sender.getPipedWriter());  
  9.     }  
  10.   
  11.     public void run() {  
  12.         try {  
  13.             while (true) {  
  14.                 // Blocks until characters are there:  
  15.                 System.out.println("Read: " + (char) in.read());  
  16.             }  
  17.         } catch (IOException e) {  
  18.             throw new RuntimeException(e);  
  19.         }  
  20.     }  
  21. }  
[java]  view plain copy
  1. import java.io.IOException;  
  2. import java.io.PipedReader;  
  3.   
  4. class Receiver extends Thread {  
  5.     private PipedReader in;  
  6.   
  7.     public Receiver(Sender sender) throws IOException {  
  8.         in = new PipedReader(sender.getPipedWriter());  
  9.     }  
  10.   
  11.     public void run() {  
  12.         try {  
  13.             while (true) {  
  14.                 // Blocks until characters are there:   
  15.                 System.out.println("Read: " + (char) in.read());  
  16.             }  
  17.         } catch (IOException e) {  
  18.             throw new RuntimeException(e);  
  19.         }  
  20.     }  
  21. }  
[java]  view plain copy
  1. import java.io.IOException;  
  2. import java.io.PipedReader;  
  3.   
  4. class Receiver extends Thread {  
  5.     private PipedReader in;  
  6.   
  7.     public Receiver(Sender sender) throws IOException {  
  8.         in = new PipedReader(sender.getPipedWriter());  
  9.     }  
  10.   
  11.     public void run() {  
  12.         try {  
  13.             while (true) {  
  14.                 // Blocks until characters are there:  
  15.                 System.out.println("Read: " + (char) in.read());  
  16.             }  
  17.         } catch (IOException e) {  
  18.             throw new RuntimeException(e);  
  19.         }  
  20.     }  
  21. }  

 

PipedIO.java

Java代码   收藏代码
  1. public class PipedIO {  
  2.       
  3.     public static void main(String[] args) throws Exception {  
  4.         Sender sender = new Sender();  
  5.         Receiver receiver = new Receiver(sender);  
  6.         sender.start();  
  7.         receiver.start();  
  8.     }  
  9. }  
[java]  view plain copy
  1. public class PipedIO {  
  2.       
  3.     public static void main(String[] args) throws Exception {  
  4.         Sender sender = new Sender();  
  5.         Receiver receiver = new Receiver(sender);  
  6.         sender.start();  
  7.         receiver.start();  
  8.     }  
  9. }  
[java]  view plain copy
  1. public class PipedIO {  
  2.       
  3.     public static void main(String[] args) throws Exception {  
  4.         Sender sender = new Sender();  
  5.         Receiver receiver = new Receiver(sender);  
  6.         sender.start();  
  7.         receiver.start();  
  8.     }  
  9. }  

 

(7)实例讲解: Sender1.java, Receiver1.java, PipedIO1.java (使用

PipedInputStream,PipedOutputStream)

 

Sender1.java

Java代码   收藏代码
  1. import java.io.File;  
  2. import java.io.FileInputStream;  
  3. import java.io.IOException;  
  4. import java.io.PipedOutputStream;  
  5.   
  6. public class Sender1 extends Thread {  
  7.   
  8.     private PipedOutputStream pos;  
  9.       
  10.     private File file;  
  11.   
  12.     // 构造方法  
  13.     Sender1(PipedOutputStream pos, String fileName) {  
  14.         this.pos = pos;  
  15.         file = new File(fileName);  
  16.     }  
  17.   
  18.     // 线程运行方法  
  19.     public void run() {  
  20.         try {  
  21.             // 读文件内容  
  22.             FileInputStream fs = new FileInputStream(file);  
  23.             int data;  
  24.             while ((data = fs.read()) != -1) {  
  25.                 // 写入管道始端  
  26.                 pos.write(data);  
  27.             }  
  28.             pos.close();  
  29.         } catch (IOException e) {  
  30.             System.out.println("Sender Error" + e);  
  31.         }  
  32.     }  
  33. }  
[java]  view plain copy
  1. import java.io.File;  
  2. import java.io.FileInputStream;  
  3. import java.io.IOException;  
  4. import java.io.PipedOutputStream;  
  5.   
  6. public class Sender1 extends Thread {  
  7.   
  8.     private PipedOutputStream pos;  
  9.       
  10.     private File file;  
  11.   
  12.     // 构造方法   
  13.     Sender1(PipedOutputStream pos, String fileName) {  
  14.         this.pos = pos;  
  15.         file = new File(fileName);  
  16.     }  
  17.   
  18.     // 线程运行方法   
  19.     public void run() {  
  20.         try {  
  21.             // 读文件内容   
  22.             FileInputStream fs = new FileInputStream(file);  
  23.             int data;  
  24.             while ((data = fs.read()) != -1) {  
  25.                 // 写入管道始端   
  26.                 pos.write(data);  
  27.             }  
  28.             pos.close();  
  29.         } catch (IOException e) {  
  30.             System.out.println("Sender Error" + e);  
  31.         }  
  32.     }  
  33. }  
[java]  view plain copy
  1. import java.io.File;  
  2. import java.io.FileInputStream;  
  3. import java.io.IOException;  
  4. import java.io.PipedOutputStream;  
  5.   
  6. public class Sender1 extends Thread {  
  7.   
  8.     private PipedOutputStream pos;  
  9.       
  10.     private File file;  
  11.   
  12.     // 构造方法  
  13.     Sender1(PipedOutputStream pos, String fileName) {  
  14.         this.pos = pos;  
  15.         file = new File(fileName);  
  16.     }  
  17.   
  18.     // 线程运行方法  
  19.     public void run() {  
  20.         try {  
  21.             // 读文件内容  
  22.             FileInputStream fs = new FileInputStream(file);  
  23.             int data;  
  24.             while ((data = fs.read()) != -1) {  
  25.                 // 写入管道始端  
  26.                 pos.write(data);  
  27.             }  
  28.             pos.close();  
  29.         } catch (IOException e) {  
  30.             System.out.println("Sender Error" + e);  
  31.         }  
  32.     }  
  33. }  

 

Receiver1.java

Java代码   收藏代码
  1. import java.io.File;  
  2. import java.io.FileOutputStream;  
  3. import java.io.IOException;  
  4. import java.io.PipedInputStream;  
  5.   
  6. public class Receiver1 extends Thread {  
  7.   
  8.     private PipedInputStream pis;  
  9.     private File file;  
  10.   
  11.     // 构造方法  
  12.     Receiver1(PipedInputStream pis, String fileName) {  
  13.         this.pis = pis;  
  14.         file = new File(fileName);  
  15.     }  
  16.   
  17.     // 线程运行  
  18.     public void run() {  
  19.         try {  
  20.             // 写文件流对象  
  21.             FileOutputStream fs = new FileOutputStream(file);  
  22.             int data;  
  23.             // 从管道末端读  
  24.             while ((data = pis.read()) != -1) {  
  25.                 // 写入本地文件  
  26.                 fs.write(data);  
  27.             }  
  28.             pis.close();  
  29.         } catch (IOException e) {  
  30.             System.out.println("Receiver Error" + e);  
  31.         }  
  32.     }  
  33. }  
[java]  view plain copy
  1. import java.io.File;  
  2. import java.io.FileOutputStream;  
  3. import java.io.IOException;  
  4. import java.io.PipedInputStream;  
  5.   
  6. public class Receiver1 extends Thread {  
  7.   
  8.     private PipedInputStream pis;  
  9.     private File file;  
  10.   
  11.     // 构造方法   
  12.     Receiver1(PipedInputStream pis, String fileName) {  
  13.         this.pis = pis;  
  14.         file = new File(fileName);  
  15.     }  
  16.   
  17.     // 线程运行   
  18.     public void run() {  
  19.         try {  
  20.             // 写文件流对象   
  21.             FileOutputStream fs = new FileOutputStream(file);  
  22.             int data;  
  23.             // 从管道末端读   
  24.             while ((data = pis.read()) != -1) {  
  25.                 // 写入本地文件   
  26.                 fs.write(data);  
  27.             }  
  28.             pis.close();  
  29.         } catch (IOException e) {  
  30.             System.out.println("Receiver Error" + e);  
  31.         }  
  32.     }  
  33. }  
[java]  view plain copy
  1. import java.io.File;  
  2. import java.io.FileOutputStream;  
  3. import java.io.IOException;  
  4. import java.io.PipedInputStream;  
  5.   
  6. public class Receiver1 extends Thread {  
  7.   
  8.     private PipedInputStream pis;  
  9.     private File file;  
  10.   
  11.     // 构造方法  
  12.     Receiver1(PipedInputStream pis, String fileName) {  
  13.         this.pis = pis;  
  14.         file = new File(fileName);  
  15.     }  
  16.   
  17.     // 线程运行  
  18.     public void run() {  
  19.         try {  
  20.             // 写文件流对象  
  21.             FileOutputStream fs = new FileOutputStream(file);  
  22.             int data;  
  23.             // 从管道末端读  
  24.             while ((data = pis.read()) != -1) {  
  25.                 // 写入本地文件  
  26.                 fs.write(data);  
  27.             }  
  28.             pis.close();  
  29.         } catch (IOException e) {  
  30.             System.out.println("Receiver Error" + e);  
  31.         }  
  32.     }  
  33. }  

 

PipedIO1.java

Java代码   收藏代码
  1. import java.io.IOException;  
  2. import java.io.PipedInputStream;  
  3. import java.io.PipedOutputStream;  
  4.   
  5. public class PipedIO1 {  
  6.   
  7.     public static void main(String[] args) {  
  8.         try {  
  9.             // 构造读写的管道流对象  
  10.             PipedInputStream pis = new PipedInputStream();  
  11.             PipedOutputStream pos = new PipedOutputStream();  
  12.               
  13.             // 实现关联  
  14.             pos.connect(pis);  
  15.               
  16.             // 构造两个线程,并且启动。  
  17.             new Sender1(pos, "c:\\a1.txt").start();  
  18.             new Receiver1(pis, "c:\\a2.txt").start();  
  19.         } catch (IOException e) {  
  20.             System.out.println("Pipe Error" + e);  
  21.         }  
  22.     }  
  23. }  
[java]  view plain copy
  1. import java.io.IOException;  
  2. import java.io.PipedInputStream;  
  3. import java.io.PipedOutputStream;  
  4.   
  5. public class PipedIO1 {  
  6.   
  7.     public static void main(String[] args) {  
  8.         try {  
  9.             // 构造读写的管道流对象   
  10.             PipedInputStream pis = new PipedInputStream();  
  11.             PipedOutputStream pos = new PipedOutputStream();  
  12.               
  13.             // 实现关联   
  14.             pos.connect(pis);  
  15.               
  16.             // 构造两个线程,并且启动。   
  17.             new Sender1(pos, "c:\\a1.txt").start();  
  18.             new Receiver1(pis, "c:\\a2.txt").start();  
  19.         } catch (IOException e) {  
  20.             System.out.println("Pipe Error" + e);  
  21.         }  
  22.     }  
  23. }  
[java]  view plain copy
  1. import java.io.IOException;  
  2. import java.io.PipedInputStream;  
  3. import java.io.PipedOutputStream;  
  4.   
  5. public class PipedIO1 {  
  6.   
  7.     public static void main(String[] args) {  
  8.         try {  
  9.             // 构造读写的管道流对象  
  10.             PipedInputStream pis = new PipedInputStream();  
  11.             PipedOutputStream pos = new PipedOutputStream();  
  12.               
  13.             // 实现关联  
  14.             pos.connect(pis);  
  15.               
  16.             // 构造两个线程,并且启动。  
  17.             new Sender1(pos, "c:\\a1.txt").start();  
  18.             new Receiver1(pis, "c:\\a2.txt").start();  
  19.         } catch (IOException e) {  
  20.             System.out.println("Pipe Error" + e);  
  21.         }  
  22.     }  
  23. }  

 

 

RandomAccessFile(随机文件读写类):

(1)RandomAccessFile类:它直接继承于Object类而非InputStream/OutputStream类,从而可以实现读写文件中任何位置中的数据(只需要改变文件的读写位置的指针)。

(2)由于RandomAccessFile类实现了DataOutput与DataInput接口,因而利用它可以读写Java中的不同类型的基本类型数据(比如采用readLong()方法读取长整数,而利用readInt()方法可以读出整数值等)。

 

RandomFileRW.java

Java代码   收藏代码
  1. import java.io.IOException;  
  2. import java.io.RandomAccessFile;  
  3.   
  4. public class RandomFileRW {  
  5.   
  6.     public static void main(String args[]) {  
  7.         StringBuffer buf = new StringBuffer();  
  8.         char ch;  
  9.           
  10.         try {  
  11.             while ((ch = (char) System.in.read()) != '\n') {  
  12.                 buf.append(ch);  
  13.             }  
  14.               
  15.             // 读写方式可以为"r" or "rw"  
  16.               
  17.             /** 
  18.              * @param mode 1. r 2. rw 3. rws 4. rwd 
  19.              * "r" Open for reading only. Invoking any of the write methods of the resulting object will 
  20.              *      cause an IOException to be thrown.   
  21.              * "rw" Open for reading and writing. If the file does not already exist then an attempt will 
  22.              *      be made to create it.   
  23.              * "rws" Open for reading and writing, as with "rw", and also require that every update to the 
  24.              *      file's content or metadata be written synchronously to the underlying storage device.   
  25.              * "rwd"   Open for reading and writing, as with "rw", and also require that every update to the 
  26.              *      file's content be written synchronously to the underlying storage device.  
  27.              */  
  28.             RandomAccessFile myFileStream = new RandomAccessFile("c:\\UserInput.txt""rw");  
  29.             myFileStream.seek(myFileStream.length());  
  30.             myFileStream.writeBytes(buf.toString());  
  31.               
  32.             // 将用户从键盘输入的内容添加到文件的尾部  
  33.             myFileStream.close();  
  34.         } catch (IOException e) {  
  35.         }  
  36.     }  
  37. }  

 
 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值