您的位置:首页 > 职场人生

黑马程序员—java技术blog—第一篇 IO概述及字节流总结

2015-09-22 23:42 567 查看
 ------- <a href="http://www.itheima.com" target="blank">android培训</a>、<a
href="http://www.itheima.com" target="blank">java培训</a>、期待与您交流! ----------

IO流: 用来对本地文件或网络中的资源进行读与写数据的技术

I: Input 输入
O: Output 输出
-------------------------------
IO流的分类:
 流的方向划分:
  输入流
  输出流

  流中的数据划分:
   字节流
   字符流
 ------------------------------
IO流的划分                                                                    File----------------------文件、文件夹路径
  字节流:
   字节输入流:  InputStream, 字节输入流的所有类的超类,  抽象类-----------使用时,用其子类 FileInputStream
   字节输出流: OutputStream, 字节输出流的所有类的超类, 抽象类---------------使用时,用其子类 FileOutputStream
  字符流:
   字符输入流: Reader, 字符输入流的所有类的超类, 抽象类
   字符输出流:Writer, 字符输出流的所有类的超类, 抽象类

 通过字节输入流 ,从文件中读数据                                         
分析:
 * 1, 打开文件
 * 2, 读文件中的数据
 * 3,关闭文件
案例
//1, 打开文件
  FileInputStream fis = new FileInputStream("abc.txt");                  
  //2, 读文件中的数据
  int ch = fis.read();
  //System.out.println(ch);
  System.out.println((char)ch);
  //3,关闭文件
  fis.close();

通过字节输出流 ,向文件中 写数据

  1.构造方法:
 * public FileOutputStream(String name)
                 throws FileNotFoundException
2.案列
//打开文件
FileOutputStream fos = new FileOutputStream("abc.txt");
  //2,写数据到文件中
  fos.write('a');
  //3,关闭文件
  fos.close();

 FileOutputStream 操作文件的 字节输出流
构造方法:
 * FileOutputStream(String name) 通过文件的路径 来完成字节输出流的创建
 * FileOutputStream(File file) 通过FIle对象 来创建 字节输出流
 *
 * 输出流特点: 如果文件存在,直接打开; 如果文件不存在,创建后,打开
 * java.io.FileNotFoundException: Z:\123.txt (系统找不到指定的路径。)
 *
 * 方法:
 * public void close()  throws IOException  关闭此输出流并释放与此流有关的所有系统资源
 * public void flush()  throws IOException刷新此输出流并强制写出所有缓冲的输出字节
 * public void write(byte[] b) throws IOException 写入一个字节数组
 * public void write(byte[] b, int startIndex, int len) 写入字节数组的一部分
 * public abstract void write(int b) 写入一个字节
字节流中不能写入String类,即不能写入字符串。

 案例
//创建流对象
  FileOutputStream fos = new FileOutputStream("abc.txt");------------------创建基本流,同时就创建了abc.txt文件
  //写数据
  //public abstract void write(int b) 写入一个字节
  //fos.write('b');
  //public void write(byte[] b) 写入一个字节数组
  //byte[] bys = "abcde".getBytes();
  //fos.write(bys);
 
  //public void write(byte[] b, int startIndex, int len) 写入字节数组的一部分
  byte[] bys = "abcde".getBytes();
  fos.write(bys, 0, 3);
 
  //关闭流
  //public void close()  关闭此输出流并释放与此流有关的所有系统资源
  fos.close();

close与flush的区别
方法:
 * public void close()  throws IOException  关闭此输出流并释放与此流有关的所有系统资源
 * public void flush()  throws IOException刷新此输出流并强制写出所有缓冲的输出字节
 *   ------------------------------
 * close关闭 与 flush刷新  二者的区别?
 * 调用close(), 流闭关了,不能再写入数据
 * 调用flush(),刷新流中的数据到文件中,流没有关闭,可以继续写入数据

 ------- <a href="http://www.itheima.com" target="blank">android培训</a>、<a
href="http://www.itheima.com" target="blank">java培训</a>、期待与您交流! ----------
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: