Java学习笔记38(字符流)

字符输出流:Writer类:使用时候需要它的子类

局限性:只能写文本文件,无法写其他文件

方法:

package demo;

import java.io.FileWriter;
import java.io.IOException;

public class WriterDemo {
    public static void main(String[] args) throws IOException {
        FileWriter fw = new FileWriter("d:\java.txt");
        fw.write(100);// 写入:d
        fw.flush();
        // 注意每一次写都要使用flush方法
        char[] cs = { 'a', 'b', 'c', 'd', 'e' };
        fw.write(cs);// 写入:abcde
        fw.flush();
        fw.write(cs, 1, 2);// 写入:bc
        fw.flush();

        fw.write("java");// 写入:java
        fw.flush();

        fw.close();
    }
}

字符输入流读文本:Reader类

同样有局限性,只能读文本文件

方法(使用上边写好的java.txt文本):

还是两种方式:

package demo;

import java.io.FileReader;
import java.io.IOException;

public class ReaderDemo {
    public static void main(String[] args) throws IOException {
        FileReader fr = new FileReader("d:\java.txt");
        int len = 0;
        while ((len = fr.read()) != -1) {
            System.out.print((char) len);
        }
        fr.close();
      
        System.out.println("两种方法分界线");

        FileReader fr1 = new FileReader("d:\java.txt");
        char[] ch = new char[1024];
        while ((len = fr1.read(ch)) != -1) {
            System.out.print(new String(ch, 0, len));
        }
        fr1.close();
    }
}

复制文本文件:

package demo;

import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

/*
 *  字符流复制文本文件,而且必须是文本文件
 *  字符流查询本机默认的编码表,简体中文GBK
 *  FileReader读取数据源
 *  FileWriter写入到数据目的
 */
public class Copy {
    public static void main(String[] args) {
        FileReader fr = null;
        FileWriter fw = null;
        try {
            fr = new FileReader("c:\1.txt");
            fw = new FileWriter("d:\1.txt");
            char[] cbuf = new char[1024];
            int len = 0;
            while ((len = fr.read(cbuf)) != -1) {
                fw.write(cbuf, 0, len);
                fw.flush();
            }

        } catch (IOException ex) {
            System.out.println(ex);
            throw new RuntimeException("复制失败");
        } finally {
            try {
                if (fw != null)
                    fw.close();
            } catch (IOException ex) {
                throw new RuntimeException("释放资源失败");
            } finally {
                try {
                    if (fr != null)
                        fr.close();
                } catch (IOException ex) {
                    throw new RuntimeException("释放资源失败");
                }
            }
        }
    }
}
原文地址:https://www.cnblogs.com/xuyiqing/p/8288395.html