• java_I/O字符流


                                                                           I/O流(Stream)

    INPUT:输入流,从文件里读OUPUT:输出流,写内容到文件

    IO流分为:字符流和字节流

    字符流:处理纯文本文件。

    字节流:处理可以所有文件。

    字符输出流测试:


    @Test
    public void test1() {   //字符输出流

    FileWriter fw = null;
    try {
    fw = new FileWriter("./aaa.txt",true);
    fw.write("学习java第十二节课");
    } catch (IOException e) {
    e.printStackTrace();
    } finally {
    try {
    if (fw != null) {
    fw.close();
    }
    } catch (IOException e) {
    e.printStackTrace();
    }
    }
    }

    测试结果如下:

    字符输入流测试:

      @Test
    public void test2() {  //字符输入流

    FileReader fr = null;
    try {

    fr = new FileReader("./aaa.txt");
    char[] buffer = new char[4];      //每次读取的最大长度

    int len = 0;
    while ((len = fr.read(buffer)) != -1) {
    //read方法:
                //1、从文件中读取的内容会依次放入buffer数组中
                //2、要么读满数组,要么文件结束
                //3、如果文件已经到达最后的位置,就会返回-1
    System.out.println(new String(buffer, 0, len));
    }
    } catch (IOException e) {
    e.printStackTrace();
    } finally {
    try {
    if (fr != null) {
    fr.close();
    }
    } catch (IOException e) {
    e.printStackTrace();
    }
    }
    }

    测试结果如下:

                     学习java第十二节课
                     Process finished with exit code 0
     
     带缓冲区的字符流和字节流:
    缓冲区的作用:减少调用本地API的次数,从而优化系统的开销,缓冲输入流从被称为缓冲区(buffer)的存储器区域读出数据;仅当缓冲区是空时,本地输入 API 才被调用。同样,缓冲输出流,将数据写入到缓存区,只有当缓冲区已满才调用本机输出 API。
    @Test
    public void test6(){ //将aaa.txt复制到ccc.txt
    FileWriter fw=null;
    BufferedWriter bw=null;
    FileReader fr=null;
    BufferedReader br=null;
    try {

    fr=new FileReader("./aaa.txt");
    br=new BufferedReader(fr); //将读取的内容放入缓冲区

    fw = new FileWriter("./ccc.txt");
    bw=new BufferedWriter(fw);

    String line=null;
    while ((line=br.readLine())!=null){ //将缓冲区的内容一个一个取出
    System.out.println(line);
    bw.write(line); //将取出的值放入写缓冲区
    bw.flush(); //将缓冲区的内容写出
    }

    } catch (IOException e) {
    e.printStackTrace();
    }finally {
    try {
    if (bw != null) {

    bw.close();
    }
    } catch (IOException e) {
    e.printStackTrace();
    }
    try {
    if (br != null) {
    br.close();
    }
    } catch (IOException e) {
    e.printStackTrace();
    }
    }
    }


  • 相关阅读:
    protected、public、private
    第十五章 面向对象程序设计
    第十四章 重载运算与类型转换
    聚合类
    explicit构造函数
    allocator类
    直接管理内存——new和delete
    智能指针
    Bugku-CTF之点击一百万次
    Bugku-CTF之flag在index里
  • 原文地址:https://www.cnblogs.com/zhouchangyang/p/10638573.html
Copyright © 2020-2023  润新知