Java读取,输出文件的几种方式

今天需求需要读取文件,写着写着发现自己Java IO的使用体系已经成了一坨粥,乱得很,字节流字符流,缓冲流,打印流杂在了一起,实在惭愧,于是在这儿总结一下,也方便自己遗忘时温习。

字节流

输入字节流 FileInputStream

 File file = new File("C:\\Users\\suika\\Desktop\\test.txt");
 StringBuffer buffer = new StringBuffer();
 FileInputStream inputStream = null;
 try {
     inputStream = new FileInputStream(file);
     byte[] buf = new byte[1024];
     int len = 0;
     while ((len = inputStream.read(buf)) != -1) {
         String s = new String(buf, 0, len);
         buffer.append(s);
     }
     System.out.println(buffer.toString());
 } catch (Exception e) {
     e.printStackTrace();
 } finally {
     try {
         inputStream.close();
     } catch (IOException e) {
         e.printStackTrace();
     }
 }

输出字节流

File file = new File("C:\\\\Users\\\\suika\\\\Desktop\\\\test.txt");
FileOutputStream outputStream = null;
try {
   outputStream = new FileOutputStream(file, true);
   byte[] buf = "这是输出字节流".getBytes();
   outputStream.write(buf, 0 , buf.length);
} catch (Exception e) {
   e.printStackTrace();
} finally {
   try {
       outputStream.close();
   } catch (IOException e) {
       e.printStackTrace();
   }
}

字符流

输入字符流

  File file = new File("C:\\\\Users\\\\suika\\\\Desktop\\\\test.txt");
  FileReader fileReader = null;
  try {
      StringBuffer buffer = new StringBuffer();
      fileReader = new FileReader(file);
      char[] buf = new char[1024];
      int line = 0;
      while ((line = fileReader.read(buf)) != -1) {
          buffer.append(new String(buf, 0, line));
      }
      System.out.println(buffer.toString());
  } catch (Exception e) {
      e.printStackTrace();
  } finally {
      try {
          fileReader.close();
      } catch (IOException e) {
          e.printStackTrace();
      }
  }

输出字符流

使用的时候奇怪的发现FileWriter没有更新,只有覆盖

  File file = new File("C:\\\\Users\\\\gaofeng\\\\Desktop\\\\test.txt");
  FileWriter fileWriter = null;
  try {
      fileWriter = new FileWriter(file);
      String s = "这是新增的内容";
      fileWriter.write(s);
  } catch (IOException e) {
      e.printStackTrace();
  } finally {
      try {
          fileWriter.close();
      } catch (IOException e) {
          e.printStackTrace();
      }
  }
未完待续~~~~~~~~~~~~
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值