zoukankan      html  css  js  c++  java
  • java_day14_字符流,字节流

    IO流-字节流,字符流

    一,第一个轮子--关流

      将关流写成一个方法,以后无论有多少个需要关的流,只需调用方法传入要关闭的流即可

     

    public static void closeAll(Closeable ...closeables){
    if(closeables == null){
    return;
    }
    for (Closeable closeable : closeables) {
    if (closeable != null) {
    try {
    closeable.close();
    } catch (IOException e) {
    e.printStackTrace();
    }
    }
    }
    }

    二,BufferedInputStream和BufferedOutputStream字节流

      File srcFile = new File(srcPath);

      File desFile = new File(desPath);

      BufferedInputStream bis = new BufferedInputStream(new FileInputStream(srcFile);

      BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(desFile);

      int pos = 0; //pos=>position

      byte[] buff = new byte[1024];

      while((pos = bis.read(buff)) != -1){

        bos.write(buff,0,pos);

      }

      bos.flush();//BufferedOutputStream后面要加flush,无论bos里面的数据满没满都将里面的数据写进硬盘中.

      IOUtils.closeAll(bis,bos);//引用方法关流

    三,BufferedReader和PrintWriter字符流

      1,BufferedReader:输入流

      File file = new File("text.txt");

      BufferedReader reader = new BufferedRreader(new InputStreamReader(FileInputStream(file)));//创建字符流的对象

      String line = "";

      StringBuilder sb = new StringBuilder();//创建拼接字符串的对象

      while((line = reader.readLine()) != null){

      sb.append(line).append(" ");//手动拼接换行

      }

      String result = sb.toString();//转换成字符串

      IOUtils.colseAll(reader);//调用方法关流

     

      2.PrintWriter:输出流

      File file = new File("text.txt");

      PrintWriter pw = new PrintWriter(new OutputSreamWriter(new FileOutputStream(file)));//创建字符输入流对象

      pw.println(1);//写入数字,换行

      pw.print("你好");//写入字符串,不换行

      pw.flush();//同上

      IOUtils.closeAll(pw);//关流

        

  • 相关阅读:
    李阳疯狂英语精选365句
    线程 notify,与notifyAll 的区别
    关于Logger,Tomcat 的Logger是如何工作的
    知豆 源
    关于好多继承的问题,我们应该如何去理解
    5+1+2
    wu xing
    ALBPM Time Question
    推荐书集
    “疯狂”的定义
  • 原文地址:https://www.cnblogs.com/memo-song/p/8858081.html
Copyright © 2011-2022 走看看