zoukankan      html  css  js  c++  java
  • 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();
    }
    }
    }


  • 相关阅读:
    poj 3253 Fence Repair (优先队列,哈弗曼)
    容斥原理 (转载)
    poj 1088 滑雪 DP(dfs的记忆化搜索)
    饭卡 01背包 + 贪心
    N分之一 竖式除法模拟
    poj2325 大数除法+贪心
    优先队列重载运算符< 以及初始化列表
    POJ 2718 Smallest Difference(贪心 or next_permutation暴力枚举)
    HASH算法
    字符串匹配算法——KMP算法
  • 原文地址:https://www.cnblogs.com/zhouchangyang/p/10638573.html
Copyright © 2011-2022 走看看