IO流—字符流

时间:2019-11-19
本文章向大家介绍IO流—字符流,主要包括IO流—字符流使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

字符流

只能读写文本文件

Reader 抽象类 字符输出流的父类

Writer 抽象类 字符输出流的父类

字符转换输出流:

OutputStreamWriter(OutputStream out):创建使用默认字符编码的 OutputStreamWriter

OutputStreamWriter(OutputStream out, String charsetName) :创建使用指定字符集的 OutputStreamWriter

案例1:

public class MyTest {
    public static void main(String[] args) throws IOException {
       //输出流,所关联的文件如果不存在则自动创建
        OutputStreamWriter out = new OutputStreamWriter(new FileOutputStream("a.txt"));
        //往文件中写入数据
        out.write('你'); //一次写入一个字符
        out.write('好');
        out.flush(); //字符流要刷新一下
        out.write('你'); //一次写入一个字符
        out.write('好');
        out.write('你'); //一次写入一个字符
        out.write('好');
        out.flush();
        out.write("好好学习天天向上"); //一次写入一个字符串
        out.write("好好学习天天向上",0,6); //一次写入字符串的一部分,
        out.write("\r\n");//换行
        char[] chars = {'a', 'b', 'c', 'd', '爱', '你', '呦'};
        out.write(chars); //一次希尔一个字符数组
        out.write("\r\n");
        out.write(chars,4,3);//一次写入字符数组的一部分
        //释放资源
        out.close(); //刷新并关闭
    }
}

案例2:

public class MyTest2 {
    public static void main(String[] args) throws IOException {
        //参数2 可以指定码表 GBK UTF-8
        OutputStreamWriter out = new OutputStreamWriter(new FileOutputStream("b.txt",true),"UTF-8");
        out.write("我们使用GBK编码写入");
        out.write("\r\n");
        out.write("我们使用GBK编码写入");
        out.write("\r\n");
        out.flush();//字符流记得刷新

        //释放资源
        out.close();
    }

字符转换输入流

InputStreamReader(InputStream in): 创建一个使用默认字符集的 InputStreamReader。

InputStreamReader(InputStream in, String charsetName):创建使用指定字符集的 InputStreamReader

案例1:字符转换流读取单个字符

public class MyTest {
    public static void main(String[] args) throws IOException {
       // InputStreamReader 是字节流通向字符流的桥梁:它使用指定的 charset 读取字节并将其解码为字符
        //输入流 所关联的文件,如果不存在就报错
        InputStreamReader in = new InputStreamReader(new FileInputStream("c.txt"));
        //读取文件中的数据
        int ch = in.read(); //一次读取一个字符,如果读取不到返回-1 使用-1 就可以判断文件释放读取完毕
        System.out.println((char)ch);
        ch = in.read(); //一次读取一个字符
        System.out.println((char) ch);
        ch = in.read(); //一次读取一个字符
        System.out.println((char) ch);
        ch = in.read(); 

        in.close();

案例2:字符输入流把字符出租转换成字符串

public class MyTest2 {
    public static void main(String[] args) throws IOException {
        InputStreamReader in = new InputStreamReader(new FileInputStream("a.txt"));
        char[] chars = new char[1024];
        int len = in.read(chars); //返回值是读取到的有效字符个数
        //方式1:把字符数组转换成字符串
        String s = new String(chars, 0, len);
        System.out.println(s);
        //方式2:把字符数组转换成字符串
        String s1 = String.valueOf(chars, 0, len);
        System.out.println(s1);
        System.out.println("====================================");
        char[] chars2 = new char[1024];
        InputStreamReader in2 = new InputStreamReader(new FileInputStream("a.txt"));
        //一次读取一部分字符,填充到字符数组中
        int len2 = in2.read(chars2, 0, 10);
        for (char c : chars2) {
            System.out.println(c);
        }
    }
}

案例3:使用字符流一次读取一个字符,写一个字符来复制文本文件

public class MyTest3 {
    public static void main(String[] args) throws IOException {
        InputStreamReader in = new InputStreamReader(new FileInputStream("MyTest.java"));

        OutputStreamWriter out = new OutputStreamWriter(new FileOutputStream("C:\\Users\\jjh\\Desktop\\a.txt"));
        //一次读取一个字符,写一个字符来复制
        int len=0;//定义一个变量,来记录读取的字符
        while ((len=in.read())!=-1){
            out.write(len);
            out.flush();
        }
       //释放资源
        in.close();
        out.close();
    }
}

案例4:使用字符数组充当缓冲区来复制文本文件

public class MyTest4 {
    public static void main(String[] args) throws IOException {
        InputStreamReader in = new InputStreamReader(new FileInputStream("MyTest.java"));

        OutputStreamWriter out = new OutputStreamWriter(new FileOutputStream("C:\\Users\\ShenMouMou\\Desktop\\b.txt"));
        //定义一个字符数组,来充当缓冲区
        char[] chars = new char[1000];
        //定义一个变量,用来记录读取到的有效字符个数
        int len=0;
        while ((len=in.read(chars))!=-1){
            System.out.println("循环次数");
            out.write(chars,0,len);
            out.flush();
        }
        //释放资源
        in.close();
        out.close();
    }
}

便捷字符流

FileReader(File file):在给定从中读取数据的 File 的情况下创建一个新 FileReader

FileReader(String fileName):在给定从中读取数据的文件名的情况下创建一个新 FileReader

FileReader(File file):在给定从中读取数据的 File 的情况下创建一个新 FileReader。

FileReader(String fileName):根据给定的 File 对象构造一个 FileWriter 对象

public class MyTest {
    public static void main(String[] args) throws IOException {
        //父类-------------------------子类
        //OutputStreamWriter-----------FileWriter
        //InputStreamReader------------- FileReader
        //便捷字符流,的缺点是不能指定编码表,用的是平台默认码表
        FileReader in = new FileReader("a.txt");
        FileWriter out = new FileWriter("aa.txt");

        //定义一个字符数组,来充当缓冲区
        char[] chars = new char[1000];
        //定义一个变量,用来记录读取到的有效字符个数
        int len = 0;
        while ((len = in.read(chars)) != -1) {
            System.out.println("循环次数");
            out.write(chars, 0, len);
            out.flush();
        }
        //释放资源
        in.close();
        out.close();
    }
}

高效的字符流

BufferedReader(Reader in): 创建一个使用默认大小输入缓冲区的缓冲字符输入流

BufferedWriter(Writer out) :创建一个使用默认大小输出缓冲区的缓冲字符输出流

public class MyTest {
    public static void main(String[] args) throws IOException {
        BufferedReader bfr = new BufferedReader(new InputStreamReader(new FileInputStream("a.txt")));
       // BufferedReader bfr2 = new BufferedReader(new FileReader("a.txt"));
       // BufferedWriter bfw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream("aaa.txt")));
        BufferedWriter bfw = new BufferedWriter(new FileWriter("aaaa.txt"));
//以上两种都可以传参 FileReader和FileWriter不能追加而且不能设置码表 只能用平台默认编码表
        char[] chars = new char[1000];
        int len=0;
        while ((len=bfr.read(chars))!=-1){
            bfw.write(chars,0,len);
            bfw.flush();
        }

        bfw.close();
        bfr.close();
    }
}

高效字符流的两个特有方法

BufferedReader readLine() :一次读取一行内容

BufferedWriter newLine():写入换行符且具有平台兼容性

案例1:高效字符流采用读取一行写入一行的方式来复制文本文件

public class MyTest2 {
    public static void main(String[] args) throws IOException {
        BufferedReader bfr = null;
        BufferedWriter bfw = null;
            bfr = new BufferedReader(new InputStreamReader(new FileInputStream("MyTest.java")));
            bfw = new BufferedWriter(new FileWriter("test.java"));
            //定义一个变量来记录读取到的每一行
            String line = null;
            //String s = bfr.readLine();
            while ((line = bfr.readLine()) != null) { //注意一行一行的读取,读取不到返回null
                bfw.write(line);
                //bfw.write("\r\n");
                bfw.newLine();//写个换号符
                bfw.flush();
            }
            }
    }

字符流的案例演示

案例1:把ArrayList集合中的字符串数据存储到文本文件

public class MyTest {
    public static void main(String[] args) throws IOException {
        ArrayList<String> list = new ArrayList<>();
        list.add("张飞");
        list.add("赵云");
        list.add("马超");
        list.add("关羽");
        list.add("黄忠");
        BufferedWriter bfw = new BufferedWriter(new FileWriter("name.txt"));
        for (String s : list) {      //遍历集合
            bfw.write(s);
            bfw.newLine();
            bfw.flush();
        }
        bfw.close();
     }
}

案例2:从文本文件中读取数据(每一行为一个字符串数据) 到集合中,并遍历集合

public class MyTest2 {
    public static void main(String[] args) throws IOException {
        BufferedReader bfr = new BufferedReader(new FileReader("name.txt"));
        ArrayList<String> list = new ArrayList<>();
        while (true) {
            String s = bfr.readLine();
            if (s == null) {
                break;
            }
            list.add(s.trim());//去掉空格
        }
        System.out.println(list);
    }

案例3:从随机名单里面抽取一个人

public class MyTest3 {
    public static void main(String[] args) throws IOException {
        BufferedReader bfr = new BufferedReader(new FileReader("name.txt"));
        ArrayList<String> list = new ArrayList<>();
        while (true) {
            String s = bfr.readLine();
            if (s == null) {
                break;
            }
            list.add(s.trim());
        }
      //生成一个随机索引
        Random random = new Random();
        int index = random.nextInt(list.size()); //0----9
        System.out.println(index);//打印出索引
        System.out.println(list.get(index));//打印出索引所对的人名
    }
}

原文地址:https://www.cnblogs.com/godles/p/11887348.html