java包含关于输入输出流_JAVA IO 输入输出流

2-1)字符输入流Reader

96da84f18c3a01467cd9a33d304a208c.png

在上面的继承关系图中可以看出:

1.    Reader是所有的输入字符流的父类,它是一个抽象类。

2.    CharReader、StringReader是两种基本的介质流,它们分别将Char数组、String中读取数据。PipedReader是从与其它线程共用的管道中读取数据。

3.    BufferedReader很明显就是一个装饰器,它和其子类负责装饰其它Reader对象。

4.    FilterReader是所有自定义具体装饰流的父类,其子类PushbackReader对Reader对象进行装饰,会增加一个行号。

5.    InputStreamReader是一个连接字节流和字符流的桥梁,它将字节流转变为字符流。FileReader可以说是一个达到此功能、常用的工具类,在其源代码中明显使用了将FileInputStream转变为Reader的方法。我们可以从这个类中得到一定的技巧。Reader中各个类的用途和使用方法基本和InputStream中的类使用一致。后面会有Reader与InputStream的对应关系。

4beca9ca8eae825fc6c9ec66e4af7b24.png

主要方法:

(1) public int read() throws IOException; //读取一个字符,返回值为读取的字符

(2) public int read(char cbuf[]) throws IOException; /*读取一系列字符到数组cbuf[]中,返回值为实际读取的字符的数量*/

(3) public abstract int read(char cbuf[],int off,int len) throws IOException; /*读取len个字符,从数组cbuf[]的下标off处开始存放,返回值为实际读取的字符数量,该方法必须由子类实现*/

2-2)字符输出流Writer

ea939146a20dec20d483f02ffcb003c4.png

在上面的关系图中可以看出:

1.    Writer是所有的输出字符流的父类,它是一个抽象类。

2.    CharArrayWriter、StringWriter是两种基本的介质流,它们分别向Char数组、String中写入数据。PipedWriter是向与其它线程共用的管道中写入数据,

3.    BufferedWriter是一个装饰器为Writer提供缓冲功能。

4.    PrintWriter和PrintStream极其类似,功能和使用也非常相似。

5.    OutputStreamWriter是OutputStream到Writer转换的桥梁,它的子类FileWriter其实就是一个实现此功能的具体类(具体可以研究一SourceCode)。功能和使用和OutputStream极其类似.

e3330c2afaa0381c603775c053a418a0.png

主要方法:

(1)  public void write(int c) throws IOException; //将整型值c的低16位写入输出流

(2)  public void write(char cbuf[]) throws IOException; //将字符数组cbuf[]写入输出流

(3)  public abstract void write(char cbuf[],int off,int len) throws IOException; //将字符数组cbuf[]中的从索引为off的位置处开始的len个字符写入输出流

(4)  public void write(String str) throws IOException; //将字符串str中的字符写入输出流

(5)  public void write(String str,int off,int len) throws IOException; //将字符串str 中从索引off开始处的len个字符写入输出流

2-3)代码示例

由于文件编码的原因,以下代码输出的文件中文可能为乱码,要解决需要知道原文件编码并以字流输入,转化为字符流后可以以正确的编码方式输出。(代码见3、字符流和字节流的转换)

8f900a89c6347c561fdf2122f13be562.png

961ddebeb323a10fe0623af514929fc1.png

package com.javaTest.io;

import java.io.*;

public class IoTest3 {

public static void main(String[] args) {

Reader file = null;

Writer ofile = null;

try {

file = new FileReader("D:\\test" + File.separator + "111.txt");

ofile = new FileWriter("D:\\test" + File.separator + "222.txt");

int r;

while ((r = file.read()) != -1) {

ofile.write(r);

}

} catch (Exception e) {

e.printStackTrace();

} finally {

try {

file.close();

ofile.close();

} catch (IOException e) {

e.printStackTrace();

}

}

}

}

View Code

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值