java -io字符流FileWrite操作演示

FileWriter字符输出流演示:

  1. /*
  2. * FiileWriter 字符流的操作
  3. * FileWriter 的构造方法 可传递 File类型 还可以传递String类型
  4. *
  5. * 方法 :
  6. * write(int c) 传递一个字节
  7. * write(char[] a ) 传递一个字符数组
  8. * write(char[]a , 开始索引 , 传递几个)
  9. * write(String s) 传递一个字符串
  10. *
  11. * 注意:写完之后一定要刷新缓冲区 不然数据 写入不进
  12. * 对象.flush()
  13. * */
  14. public static void main(String[] args) throws Exception{
  15. FileWriter fw = new FileWriter("E:gu.txt",true);
  16. //写入一个字节
  17. fw.write(97+" "); //传递 int 数据 会自动查询 编码表
  18. fw.flush();
  19. //写入一个字符数组
  20. char[] a = {'a','b','c'};
  21. fw.write(a);
  22. fw.flush();
  23. //写入一部分字符数组
  24. fw.write(a,0,2);
  25. fw.flush();
  26. //写入一个字符串
  27. fw.write(" "+"古斌牛逼");
  28. fw.flush();
  29. //关闭数据流
  30. fw.close();
  31. }

运行结果如下图:

使用字符输入流  来读取文件  注意只能读取文本  !!!

  1. //字符输入流 读取文本功能 实现
  2. //注意 只能读文本
  3. public static void main(String[] args)throws IOException {
  4. FileReader fr = new FileReader("E:gubin/1.txt");
  5. int len = 0;
  6. char[] cbuff = new char[1024];
  7. while((len = fr.read(cbuff))!=-1) {
  8. System.out.println(new String(cbuff, 0, len));
  9. }
  10. fr.close();
  11. }
  12.  
原文地址:https://www.cnblogs.com/gu-bin/p/10052945.html