Java IO之Reader/Writer

Reader和Writer:
Java 1.1对基本的I/O进行了修改,增加了Reader/Writer,但它们并不是用来替代InputStream和OutputStream的。InputStream/OutputStream面向字节,而Reader/Writer兼容Unicode且面向字符。

适配器:
有的时候我们必须把来自于“字节”层次结构中的类和来自“字符”层次结构中的类结合起来使用。为了实现这个目的,需要用到“适配器(Adapter)”类。InputStreamReader可以把InputStream转换为Reader,OutputStreamWriter可以把OutputStream转换为Writer。

Reader的子类:

CharArrayReader    对应于ByteArrayInputStream
FileReader         Reader/InputStreamReader下的子类,对应于FileInputStream
PipedReader        对应于PipedInputStream
StringReader       对应于StringBufferInputStream(已废弃)
FilterReader       对应于FilterInputStream
BufferedReader     对应于BufferInputStream,但它是直接继承Reader的。
LineNumberReader   Reader/BufferedReader下的子类,对应于LineNumberInputStream。
PushbackReader     Reader/FilterReader下的子类,对应于PushbackInputStream。

Writer的子类:

CharArrayWriter    对应于ByteArrayOutputStream
FileWriter         Reader/InputStreamReader下的子类,对应于FileOutputStream
PipedWriter        对应于PipedOutputStream
StringWriter       无相应的类
FilterWriter       对应于FilterOutputStream(抽象类,但没有子类)
BufferedWriter     对应于BufferOutputStream,但它是直接继承Reader的。
PrintWriter        对应于PrintStream

代码实例:
1 CharArrayReader/CharArrayWriter

    public void testCharArray(){
        char[] c={'a','b','c','d'};
        CharArrayReader r=new CharArrayReader(c);
        r.skip(2);
        char temp=(char) r.read();
        CharArrayWriter w=new CharArrayWriter();
        w.write(temp);
        System.out.println(w.size());
        System.out.println(w.toString());
    }
    /*
    Output:
    1
    c
    */

2 FileReader/FileWriter

    public void testFile() {
        File f=new File("FileReaderWriter.txt");
        FileWriter fw=new FileWriter(f);
        fw.write("Hello,this string is writed by FileWriter.");
        /* 此时数据还在缓冲区,需要刷新*/
        fw.flush();
        FileReader fr=new FileReader(f);
        int flag=0;
        while (flag!=-1){
            flag=fr.read();
            System.out.print((char)flag);
        }
    }
    /*
    Output:
    Hello,this string is writed by FileWriter.
    */

3 BufferedReader/BufferWriter
通常建议使用BufferedReader包装所有其read()操作开销可能较大的Reader,如FileReader;使用BufferedWriter包装所有其write()操作开销可能较大的Writer。

    public void testBuffered() {
        File f=new File("FileReaderWriter.txt");
        BufferedWriter bw=new BufferedWriter(new FileWriter(f));
        bw.write("This is the first day.\nThis is the second day.");
        bw.flush();
        BufferedReader br=new BufferedReader(new FileReader(f));        FileReader fr=new FileReader(f);
        String s=br.readLine();
        while(s!=null){
            System.out.println(s);
            s=br.readLine();
        }
    }
    /*
    Output:
    This is the first day.
    This is the second day.
    */
阅读更多
文章标签: java Reader writer
个人分类: Java
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

加入CSDN,享受更精准的内容推荐,与500万程序员共同成长!
关闭
关闭