zoukankan      html  css  js  c++  java
  • Java连载155IO总结(二) 心悦君兮君不知

    一、四种方式分别举例

    1.FileInputStream

      InputStream is = null;
      String address = "E:\\d05_gitcode\\Java\\newJava\\src\\com\\newJava\\newFile.txt";
      int b;
      try {
       is = new FileInputStream(address);
       while ((b = is.read()) != -1) {  // 可以看出是一个字节一个字节读取的
        System.out.println((char)b);
       }

      } catch (Exception e) {
       e.printStackTrace();
      } finally {
       try {
        is.close();
       } catch (IOException e) {
        e.printStackTrace();
       }
      }

    155.1
    155.1
    • 可以看出字符是占用至少两个字节的,我们打出的都是一堆问号,这是只打印出了一个字节,而不是字符

    2.FileOutputStream

      FileOutputStream fis = null;
      try {
       fis = new FileOutputStream(address);
       fis.write("有点优秀".getBytes()); // getBytes()获取这个字符串的byte数组,下面的toCharArray()获取字符数组
       fis.close();
      } catch (IOException e) {
       e.printStackTrace();
      }
    • 这里利用了字符串带有函数getBytes(),返回了一个Byte数组,传入这个字节数组,下面的FileWriter就是传入的char数组 155.2

    3.FileReader

      FileReader fr = null;
      try {
       fr = new FileReader(address);
       while((b = fr.read()) != -1) {
        System.out.println((char)b);
       }
      } catch (IOException e) {
       e.printStackTrace();
      }

    155.3
    155.3
    • 这个就把字符给显示出来了

    4.FileWriter

      FileWriter fw = null;
      char[] arargs = "太牛逼了".toCharArray();
      try {
       fw = new FileWriter(address);
       fw.write(arargs, 0, arargs.length);
       fw.close();
      } catch (IOException e) {
       e.printStackTrace();
      }
    155.4
    155.4

    5.ByteArrayInputStream

      try {
       byte[] arr = "厉害了".getBytes(StandardCharsets.UTF_8);
       InputStream is2 = new BufferedInputStream(new ByteArrayInputStream(arr));
       byte[] flush = new byte[1024];
       int len = 0;
       while((len = is2.read(flush)) != -1) {
        System.out.println(new String(flush, 0, len));
       }
      } catch(Exception e) {
       e.printStackTrace();
      }

    6.ByteArrayOutputStream

      try {
       ByteArrayOutputStream baos = new ByteArrayOutputStream();
       byte[] info = "厉害了".getBytes();
       baos.write(info, 0, info.length);
       byte[] dest = baos.toByteArray();
       baos.close();
       } catch(Exception e) {
       e.printStackTrace();
      }

    二、源码:

  • 相关阅读:
    java 传入多个参数时报"Parameter 'XXX' not found. Available parameters are [arg1, arg0, param1,..." 解决方案
    java 判断int类型为空
    scp 传输下载
    自己开发的网页在跳转至微信公众号文章后,点击微信的返回,无法返回原网页
    nginx下Thinkphp 隐藏index.php
    ubuntu常见错误–Could not get lock /var/lib/dpkg/lock解决
    apt-get update 和 upgrade 的区别
    php 取某一日期的前一天
    PHP 统计数组中所有的值出现的次数 array_count_values 函数
    pandas之表格样式
  • 原文地址:https://www.cnblogs.com/ruigege0000/p/15721781.html
Copyright © 2011-2022 走看看