代码: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 的一般使用原则 :
一、按数据来源(去向)分类:
1 、是文件: FileInputStream, FileOutputStream, ( 字节流 )FileReader, FileWriter( 字符 )
2 、是 byte[] : ByteArrayInputStream, ByteArrayOutputStream( 字节流 )
3 、是 Char[]: CharArrayReader, CharArrayWriter( 字符流 )
4 、是 String: StringBufferInputStream, StringBufferOuputStream ( 字节流 )StringReader, StringWriter( 字符流 )
5 、网络数据流: InputStream, OutputStream,( 字节流 ) Reader, Writer( 字符流 )
二、按是否格式化输出分:
1 、要格式化输出: PrintStream, PrintWriter
三、按是否要缓冲分:
1 、要缓冲: BufferedInputStream, BufferedOutputStream,( 字节流 ) BufferedReader, BufferedWriter( 字符流 )
四、按数据格式分:
1 、二进制格式(只要不能确定是纯文本的) : InputStream, OutputStream 及其所有带 Stream 结束的子类
2 、纯文本格式(含纯英文与汉字或其他编码方式); Reader, Writer 及其所有带 Reader, Writer 的子类
五、按输入输出分:
1 、输入: Reader, InputStream 类型的子类
2 、输出: Writer, OutputStream 类型的子类
六、特殊需要:
1 、从 Stream 到 Reader,Writer 的转换类: InputStreamReader, OutputStreamWriter
2 、对象输入输出: ObjectInputStream, ObjectOutputStream
3 、进程间通信: PipeInputStream, PipeOutputStream, PipeReader, PipeWriter
4 、合并输入: 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所提供的方法,可以得到文件或目录的描述信息,这主要包括名称、所在路经、可读性、可写性、文件的长度等,还可以生成新的目录、改变文件名、删除文件、列出一个目录中所有的文件等。
- public static void main(String[] args) throws IOException {
- File f = new File("dir");
- f.createNewFile();// 创建一个.txt这个文件
- f.mkdir();// 创建一个名为.txt的目录
- /*
- * 使用绝对路径
- *
- * File f=new File("D:\\dir\\src\\A.java");
- *
- * f.createNewFile();
- */
- /*
- * 跨平台使用
- *
- * 根据不同操作系统获得对应的分隔符 File fDir=new File(File.separator);
- *
- * String strFile="dir"+File.separator+"src"+File.separator +"A.java";
- *
- * File f=new File(fDir,strFile);
- *
- * f.createNewFile();
- *
- * f.delete();//删除文件或目录
- *
- * //f.deleteOnExit();
- */
- /*
- * 在缺省的临时文件目录下创建临时文件
- *
- * for(int i=0;i<5;i++)
- *
- * {
- *
- * File f=File.createTempFile("winTemp",".tmp");
- *
- * f.deleteOnExit();//退出时删除
- *
- *
- *
- * }
- */
- /*
- * 列出指定目录下所有子目录及文件的名称
- */
- File fDir = new File(File.separator);
- String strFile = "dir" + File.separator + "src";
- File f = new File(fDir, strFile);
- String[] names = f.list();
- for (int i = 0; i < names.length; i++) {
- System.out.println(names[i]);
- }
- // 有过滤器的情况FilenameFilter是个接口
- File dir = new File(File.separator);
- String filepath = "dir" + File.separator + "src";
- /**
- * dir
- * 上级抽象路径,如果dir为null,那么程序将自动调用单个参数的File构造方法,同时将filepath路径应用到File但构造参数
- * 如果dir为//,则此路径为本文件所在磁盘根目录
- */
- File f = new File(dir, filepath);
- if (f.exists()) {
- } else {
- f.mkdirs();
- }
- String[] names = f.list(new FilenameFilter() { // 实现了FilenameFilter接口的匿名类,实现accept方法过滤文件
- @Override
- public boolean accept(File dir, String name) {
- System.out.println(name.indexOf(".java"));
- return name.indexOf(".java") != -1;
- }
- });
- for (int i = 0; i < names.length; i++) {
- System.out.println(names[i]);
- }
- }
- public static void main(String[] args) throws IOException {
- File f = new File("dir");
- f.createNewFile();// 创建一个.txt这个文件
- f.mkdir();// 创建一个名为.txt的目录
- /*
- * 使用绝对路径
- *
- * File f=new File("D:\\dir\\src\\A.java");
- *
- * f.createNewFile();
- */
- /*
- * 跨平台使用
- *
- * 根据不同操作系统获得对应的分隔符 File fDir=new File(File.separator);
- *
- * String strFile="dir"+File.separator+"src"+File.separator +"A.java";
- *
- * File f=new File(fDir,strFile);
- *
- * f.createNewFile();
- *
- * f.delete();//删除文件或目录
- *
- * //f.deleteOnExit();
- */
- /*
- * 在缺省的临时文件目录下创建临时文件
- *
- * for(int i=0;i<5;i++)
- *
- * {
- *
- * File f=File.createTempFile("winTemp",".tmp");
- *
- * f.deleteOnExit();//退出时删除
- *
- *
- *
- * }
- */
- /*
- * 列出指定目录下所有子目录及文件的名称
- */
- File fDir = new File(File.separator);
- String strFile = "dir" + File.separator + "src";
- File f = new File(fDir, strFile);
- String[] names = f.list();
- for (int i = 0; i < names.length; i++) {
- System.out.println(names[i]);
- }
- // 有过滤器的情况FilenameFilter是个接口
- File dir = new File(File.separator);
- String filepath = "dir" + File.separator + "src";
- /**
- * dir
- * 上级抽象路径,如果dir为null,那么程序将自动调用单个参数的File构造方法,同时将filepath路径应用到File但构造参数
- * 如果dir为//,则此路径为本文件所在磁盘根目录
- */
- File f = new File(dir, filepath);
- if (f.exists()) {
- } else {
- f.mkdirs();
- }
- String[] names = f.list(new FilenameFilter() { // 实现了FilenameFilter接口的匿名类,实现accept方法过滤文件
- @Override
- public boolean accept(File dir, String name) {
- System.out.println(name.indexOf(".java"));
- return name.indexOf(".java") != -1;
- }
- });
- for (int i = 0; i < names.length; i++) {
- System.out.println(names[i]);
- }
- }
- public static void main(String[] args) throws IOException {
- File f = new File("dir");
- f.createNewFile();// 创建一个.txt这个文件
- f.mkdir();// 创建一个名为.txt的目录
- /*
- * 使用绝对路径
- *
- * File f=new File("D:\\dir\\src\\A.java");
- *
- * f.createNewFile();
- */
- /*
- * 跨平台使用
- *
- * 根据不同操作系统获得对应的分隔符 File fDir=new File(File.separator);
- *
- * String strFile="dir"+File.separator+"src"+File.separator +"A.java";
- *
- * File f=new File(fDir,strFile);
- *
- * f.createNewFile();
- *
- * f.delete();//删除文件或目录
- *
- * //f.deleteOnExit();
- */
- /*
- * 在缺省的临时文件目录下创建临时文件
- *
- * for(int i=0;i<5;i++)
- *
- * {
- *
- * File f=File.createTempFile("winTemp",".tmp");
- *
- * f.deleteOnExit();//退出时删除
- *
- *
- *
- * }
- */
- /*
- * 列出指定目录下所有子目录及文件的名称
- */
- File fDir = new File(File.separator);
- String strFile = "dir" + File.separator + "src";
- File f = new File(fDir, strFile);
- String[] names = f.list();
- for (int i = 0; i < names.length; i++) {
- System.out.println(names[i]);
- }
- // 有过滤器的情况FilenameFilter是个接口
- File dir = new File(File.separator);
- String filepath = "dir" + File.separator + "src";
- /**
- * dir
- * 上级抽象路径,如果dir为null,那么程序将自动调用单个参数的File构造方法,同时将filepath路径应用到File但构造参数
- * 如果dir为//,则此路径为本文件所在磁盘根目录
- */
- File f = new File(dir, filepath);
- if (f.exists()) {
- } else {
- f.mkdirs();
- }
- String[] names = f.list(new FilenameFilter() { // 实现了FilenameFilter接口的匿名类,实现accept方法过滤文件
- @Override
- public boolean accept(File dir, String name) {
- System.out.println(name.indexOf(".java"));
- return name.indexOf(".java") != -1;
- }
- });
- for (int i = 0; i < names.length; i++) {
- System.out.println(names[i]);
- }
- }
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数组通常扮演承接数据的中间角色。
- public class FileStreamDemo {
- public static void main(String[] args) {
- try {
- byte[] buffer = new byte[1024];
- // 来源文件
- FileInputStream fileInputStream = new FileInputStream(new File(args[0]));
- // 目的文件
- FileOutputStream fileOutputStream = new FileOutputStream(new File(args[1]));
- // available()可取得未读取的数据长度
- System.out.println("复制文件:" + fileInputStream.available() + "字节");
- while (true) {
- if (fileInputStream.available() < 1024) {
- // 剩余的数据比1024字节少
- // 一位一位读出再写入目的文件
- int remain = -1;
- while ((remain = fileInputStream.read()) != -1) {
- fileOutputStream.write(remain);
- }
- break;
- } else {
- // 从来源文件读取数据至缓冲区
- fileInputStream.read(buffer);
- // 将数组数据写入目的文件
- fileOutputStream.write(buffer);
- }
- }
- // 关闭流
- fileInputStream.close();
- fileOutputStream.close();
- System.out.println("复制完成");
- } catch (ArrayIndexOutOfBoundsException e) {
- System.out.println("using: java FileStreamDemo src des");
- e.printStackTrace();
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- }
- public class FileStreamDemo {
- public static void main(String[] args) {
- try {
- byte[] buffer = new byte[1024];
- // 来源文件
- FileInputStream fileInputStream = new FileInputStream(new File(args[0]));
- // 目的文件
- FileOutputStream fileOutputStream = new FileOutputStream(new File(args[1]));
- // available()可取得未读取的数据长度
- System.out.println("复制文件:" + fileInputStream.available() + "字节");
- while (true) {
- if (fileInputStream.available() < 1024) {
- // 剩余的数据比1024字节少
- // 一位一位读出再写入目的文件
- int remain = -1;
- while ((remain = fileInputStream.read()) != -1) {
- fileOutputStream.write(remain);
- }
- break;
- } else {
- // 从来源文件读取数据至缓冲区
- fileInputStream.read(buffer);
- // 将数组数据写入目的文件
- fileOutputStream.write(buffer);
- }
- }
- // 关闭流
- fileInputStream.close();
- fileOutputStream.close();
- System.out.println("复制完成");
- } catch (ArrayIndexOutOfBoundsException e) {
- System.out.println("using: java FileStreamDemo src des");
- e.printStackTrace();
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- }
- public class FileStreamDemo {
- public static void main(String[] args) {
- try {
- byte[] buffer = new byte[1024];
- // 来源文件
- FileInputStream fileInputStream = new FileInputStream(new File(args[0]));
- // 目的文件
- FileOutputStream fileOutputStream = new FileOutputStream(new File(args[1]));
- // available()可取得未读取的数据长度
- System.out.println("复制文件:" + fileInputStream.available() + "字节");
- while (true) {
- if (fileInputStream.available() < 1024) {
- // 剩余的数据比1024字节少
- // 一位一位读出再写入目的文件
- int remain = -1;
- while ((remain = fileInputStream.read()) != -1) {
- fileOutputStream.write(remain);
- }
- break;
- } else {
- // 从来源文件读取数据至缓冲区
- fileInputStream.read(buffer);
- // 将数组数据写入目的文件
- fileOutputStream.write(buffer);
- }
- }
- // 关闭流
- fileInputStream.close();
- fileOutputStream.close();
- System.out.println("复制完成");
- } catch (ArrayIndexOutOfBoundsException e) {
- System.out.println("using: java FileStreamDemo src des");
- e.printStackTrace();
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- }
PipedInputStream/PipedOutputStream(管道输入输出)
(1)它用于实现管道的二进制格式的输入输出(将一个线程的输出结果直接连接到另一个线程的输入端口,实现两者数据直接传送)。
(2) PipedReader/PipedWriter类:它用于实现管道的字符格式的输入输出。
(3)要求:操作时需要将两个端口相互连结。
(4)实现原理:
(5) 管道的连接:
方法一:是通过构造函数直接将某一个程序的输出作为另一个程序的输入,在定义对象时指明目标管道对象
方法二:是利用双方类中的任一个成员函数 connect()相连接
(6)实例讲解: Sender.java, Receiver.java, PipedIO.java (使用PipedWriter,PipedReader)
Sender.java
- import java.io.PipedWriter;
- import java.util.Random;
- class Sender extends Thread {
- private Random rand = new Random();
- private PipedWriter out = new PipedWriter();
- public PipedWriter getPipedWriter() {
- return out;
- }
- public void run() {
- while (true) {
- for (char c = 'A'; c <= 'z'; c++) {
- try {
- out.write(c);
- sleep(rand.nextInt(500));
- } catch (Exception e) {
- throw new RuntimeException(e);
- }
- }
- }
- }
- }
- import java.io.PipedWriter;
- import java.util.Random;
- class Sender extends Thread {
- private Random rand = new Random();
- private PipedWriter out = new PipedWriter();
- public PipedWriter getPipedWriter() {
- return out;
- }
- public void run() {
- while (true) {
- for (char c = 'A'; c <= 'z'; c++) {
- try {
- out.write(c);
- sleep(rand.nextInt(500));
- } catch (Exception e) {
- throw new RuntimeException(e);
- }
- }
- }
- }
- }
- import java.io.PipedWriter;
- import java.util.Random;
- class Sender extends Thread {
- private Random rand = new Random();
- private PipedWriter out = new PipedWriter();
- public PipedWriter getPipedWriter() {
- return out;
- }
- public void run() {
- while (true) {
- for (char c = 'A'; c <= 'z'; c++) {
- try {
- out.write(c);
- sleep(rand.nextInt(500));
- } catch (Exception e) {
- throw new RuntimeException(e);
- }
- }
- }
- }
- }
Receiver.java
- import java.io.IOException;
- import java.io.PipedReader;
- class Receiver extends Thread {
- private PipedReader in;
- public Receiver(Sender sender) throws IOException {
- in = new PipedReader(sender.getPipedWriter());
- }
- public void run() {
- try {
- while (true) {
- // Blocks until characters are there:
- System.out.println("Read: " + (char) in.read());
- }
- } catch (IOException e) {
- throw new RuntimeException(e);
- }
- }
- }
- import java.io.IOException;
- import java.io.PipedReader;
- class Receiver extends Thread {
- private PipedReader in;
- public Receiver(Sender sender) throws IOException {
- in = new PipedReader(sender.getPipedWriter());
- }
- public void run() {
- try {
- while (true) {
- // Blocks until characters are there:
- System.out.println("Read: " + (char) in.read());
- }
- } catch (IOException e) {
- throw new RuntimeException(e);
- }
- }
- }
- import java.io.IOException;
- import java.io.PipedReader;
- class Receiver extends Thread {
- private PipedReader in;
- public Receiver(Sender sender) throws IOException {
- in = new PipedReader(sender.getPipedWriter());
- }
- public void run() {
- try {
- while (true) {
- // Blocks until characters are there:
- System.out.println("Read: " + (char) in.read());
- }
- } catch (IOException e) {
- throw new RuntimeException(e);
- }
- }
- }
PipedIO.java
- public class PipedIO {
- public static void main(String[] args) throws Exception {
- Sender sender = new Sender();
- Receiver receiver = new Receiver(sender);
- sender.start();
- receiver.start();
- }
- }
- public class PipedIO {
- public static void main(String[] args) throws Exception {
- Sender sender = new Sender();
- Receiver receiver = new Receiver(sender);
- sender.start();
- receiver.start();
- }
- }
- public class PipedIO {
- public static void main(String[] args) throws Exception {
- Sender sender = new Sender();
- Receiver receiver = new Receiver(sender);
- sender.start();
- receiver.start();
- }
- }
(7)实例讲解: Sender1.java, Receiver1.java, PipedIO1.java (使用
PipedInputStream,PipedOutputStream)
Sender1.java
- import java.io.File;
- import java.io.FileInputStream;
- import java.io.IOException;
- import java.io.PipedOutputStream;
- public class Sender1 extends Thread {
- private PipedOutputStream pos;
- private File file;
- // 构造方法
- Sender1(PipedOutputStream pos, String fileName) {
- this.pos = pos;
- file = new File(fileName);
- }
- // 线程运行方法
- public void run() {
- try {
- // 读文件内容
- FileInputStream fs = new FileInputStream(file);
- int data;
- while ((data = fs.read()) != -1) {
- // 写入管道始端
- pos.write(data);
- }
- pos.close();
- } catch (IOException e) {
- System.out.println("Sender Error" + e);
- }
- }
- }
- import java.io.File;
- import java.io.FileInputStream;
- import java.io.IOException;
- import java.io.PipedOutputStream;
- public class Sender1 extends Thread {
- private PipedOutputStream pos;
- private File file;
- // 构造方法
- Sender1(PipedOutputStream pos, String fileName) {
- this.pos = pos;
- file = new File(fileName);
- }
- // 线程运行方法
- public void run() {
- try {
- // 读文件内容
- FileInputStream fs = new FileInputStream(file);
- int data;
- while ((data = fs.read()) != -1) {
- // 写入管道始端
- pos.write(data);
- }
- pos.close();
- } catch (IOException e) {
- System.out.println("Sender Error" + e);
- }
- }
- }
- import java.io.File;
- import java.io.FileInputStream;
- import java.io.IOException;
- import java.io.PipedOutputStream;
- public class Sender1 extends Thread {
- private PipedOutputStream pos;
- private File file;
- // 构造方法
- Sender1(PipedOutputStream pos, String fileName) {
- this.pos = pos;
- file = new File(fileName);
- }
- // 线程运行方法
- public void run() {
- try {
- // 读文件内容
- FileInputStream fs = new FileInputStream(file);
- int data;
- while ((data = fs.read()) != -1) {
- // 写入管道始端
- pos.write(data);
- }
- pos.close();
- } catch (IOException e) {
- System.out.println("Sender Error" + e);
- }
- }
- }
Receiver1.java
- import java.io.File;
- import java.io.FileOutputStream;
- import java.io.IOException;
- import java.io.PipedInputStream;
- public class Receiver1 extends Thread {
- private PipedInputStream pis;
- private File file;
- // 构造方法
- Receiver1(PipedInputStream pis, String fileName) {
- this.pis = pis;
- file = new File(fileName);
- }
- // 线程运行
- public void run() {
- try {
- // 写文件流对象
- FileOutputStream fs = new FileOutputStream(file);
- int data;
- // 从管道末端读
- while ((data = pis.read()) != -1) {
- // 写入本地文件
- fs.write(data);
- }
- pis.close();
- } catch (IOException e) {
- System.out.println("Receiver Error" + e);
- }
- }
- }
- import java.io.File;
- import java.io.FileOutputStream;
- import java.io.IOException;
- import java.io.PipedInputStream;
- public class Receiver1 extends Thread {
- private PipedInputStream pis;
- private File file;
- // 构造方法
- Receiver1(PipedInputStream pis, String fileName) {
- this.pis = pis;
- file = new File(fileName);
- }
- // 线程运行
- public void run() {
- try {
- // 写文件流对象
- FileOutputStream fs = new FileOutputStream(file);
- int data;
- // 从管道末端读
- while ((data = pis.read()) != -1) {
- // 写入本地文件
- fs.write(data);
- }
- pis.close();
- } catch (IOException e) {
- System.out.println("Receiver Error" + e);
- }
- }
- }
- import java.io.File;
- import java.io.FileOutputStream;
- import java.io.IOException;
- import java.io.PipedInputStream;
- public class Receiver1 extends Thread {
- private PipedInputStream pis;
- private File file;
- // 构造方法
- Receiver1(PipedInputStream pis, String fileName) {
- this.pis = pis;
- file = new File(fileName);
- }
- // 线程运行
- public void run() {
- try {
- // 写文件流对象
- FileOutputStream fs = new FileOutputStream(file);
- int data;
- // 从管道末端读
- while ((data = pis.read()) != -1) {
- // 写入本地文件
- fs.write(data);
- }
- pis.close();
- } catch (IOException e) {
- System.out.println("Receiver Error" + e);
- }
- }
- }
PipedIO1.java
- import java.io.IOException;
- import java.io.PipedInputStream;
- import java.io.PipedOutputStream;
- public class PipedIO1 {
- public static void main(String[] args) {
- try {
- // 构造读写的管道流对象
- PipedInputStream pis = new PipedInputStream();
- PipedOutputStream pos = new PipedOutputStream();
- // 实现关联
- pos.connect(pis);
- // 构造两个线程,并且启动。
- new Sender1(pos, "c:\\a1.txt").start();
- new Receiver1(pis, "c:\\a2.txt").start();
- } catch (IOException e) {
- System.out.println("Pipe Error" + e);
- }
- }
- }
- import java.io.IOException;
- import java.io.PipedInputStream;
- import java.io.PipedOutputStream;
- public class PipedIO1 {
- public static void main(String[] args) {
- try {
- // 构造读写的管道流对象
- PipedInputStream pis = new PipedInputStream();
- PipedOutputStream pos = new PipedOutputStream();
- // 实现关联
- pos.connect(pis);
- // 构造两个线程,并且启动。
- new Sender1(pos, "c:\\a1.txt").start();
- new Receiver1(pis, "c:\\a2.txt").start();
- } catch (IOException e) {
- System.out.println("Pipe Error" + e);
- }
- }
- }
- import java.io.IOException;
- import java.io.PipedInputStream;
- import java.io.PipedOutputStream;
- public class PipedIO1 {
- public static void main(String[] args) {
- try {
- // 构造读写的管道流对象
- PipedInputStream pis = new PipedInputStream();
- PipedOutputStream pos = new PipedOutputStream();
- // 实现关联
- pos.connect(pis);
- // 构造两个线程,并且启动。
- new Sender1(pos, "c:\\a1.txt").start();
- new Receiver1(pis, "c:\\a2.txt").start();
- } catch (IOException e) {
- System.out.println("Pipe Error" + e);
- }
- }
- }
RandomAccessFile(随机文件读写类):
(1)RandomAccessFile类:它直接继承于Object类而非InputStream/OutputStream类,从而可以实现读写文件中任何位置中的数据(只需要改变文件的读写位置的指针)。
(2)由于RandomAccessFile类实现了DataOutput与DataInput接口,因而利用它可以读写Java中的不同类型的基本类型数据(比如采用readLong()方法读取长整数,而利用readInt()方法可以读出整数值等)。
RandomFileRW.java
- import java.io.IOException;
- import java.io.RandomAccessFile;
- public class RandomFileRW {
- public static void main(String args[]) {
- StringBuffer buf = new StringBuffer();
- char ch;
- try {
- while ((ch = (char) System.in.read()) != '\n') {
- buf.append(ch);
- }
- // 读写方式可以为"r" or "rw"
- /**
- * @param mode 1. r 2. rw 3. rws 4. rwd
- * "r" Open for reading only. Invoking any of the write methods of the resulting object will
- * cause an IOException to be thrown.
- * "rw" Open for reading and writing. If the file does not already exist then an attempt will
- * be made to create it.
- * "rws" Open for reading and writing, as with "rw", and also require that every update to the
- * file's content or metadata be written synchronously to the underlying storage device.
- * "rwd" Open for reading and writing, as with "rw", and also require that every update to the
- * file's content be written synchronously to the underlying storage device.
- */
- RandomAccessFile myFileStream = new RandomAccessFile("c:\\UserInput.txt", "rw");
- myFileStream.seek(myFileStream.length());
- myFileStream.writeBytes(buf.toString());
- // 将用户从键盘输入的内容添加到文件的尾部
- myFileStream.close();
- } catch (IOException e) {
- }
- }
- }