一、流的概念

内存与存储设备之间传输数据的通道

二、流的分类

  1. 按方向

  2. 按单位

    Untitled

  3. 按功能

三、字节流

字节流的父亲(抽象类)

//InputStream 字节输入流
public int read(){}
public int read(byte[] b){}
public int read(byte[] b, int off, int len){}

// OutputStream 字节输出流
public void write(int n){}
public void write(byte[] b){}
public void write(byte[] b, int off, int len){}

3.1文件字节输入流

psvm(String[] args) throws Exception{
  // 1 创建FileInputStream 并指定文件路径
  FileInputStream fis = new FileInputStream("d:\\\\abc.txt");
  // 2 读取文件
  // fis.read();
  // 2.1单字节读取
  int data = 0;
  while((data = fis.read()) != -1){
    sout((char)data);
  }
  // 2.2 一次读取多个字节
  byte[] buf = new byte[3]; // 大小为3的缓存区
  int count = fis.read(buf); // 一次读3个
  sout(new String(buf));
  sout(count);
  int count2 = fis.read(buf); // 再读3个
  sout(new String(buf));
  sout(count2);
  
  // 上述优化后
  int count = 0;
  while((count = fis.read(buf)) != -1){
    sout(new String(buf, 0, count));
  }
  
  // 3 关闭
  fis.close();
}

3.2文件字节输出流

psvm(String[] args) throws Exception{
  // 1 创建文件字节输出流
  FileOutputStream fos = new FileOutputStream("路径", true);// true表示不覆盖 接着写 
	// 2 写入文件
  fos.write(97);
  fos.write('a');
  // String string = "hello world";
  fos.write(string.getByte());
  // 3 关闭
  fos.close();
}

3.3图片复制案例

// 1 创建流
// 1.1 文件字节输入流
FileInputStream fis = new FileInputStream("路径");
// 1.2 文件字节输出流
FileInputStream fos = new FileOutpuStream("路径");
// 2 边读边写
byte[] buf = new byte[1024];
int count = 0;
while((count = fis.read(buf)) != -1){
  fos.write(buf, 0, count);
}
// 3 关闭
fis.close();
fos.close();

3.4字节缓冲流(包装流)

// 使用字节缓冲流 读取 文件
psvm(String[] args) throws Exception{
  // 1 创建BufferedInputStream
  FileInputStream fis = new FileInputStream("路径");
  BufferedInputStream bis = new BufferedInputStream(fis);
  // 2 读取
  int data = 0;
  while((data = bis.read()) != -1){
    sout((char)data);
  }
  // 用自己创建的缓冲流
  byte[] buf = new byte[1024];
  int count = 0;
  while((count = bis.read(buf)) != -1){
    sout(new String(buf, 0, count));
  }
  
  // 3 关闭
  bis.close();
}
// 使用字节缓冲流 写入 文件
psvm(String[] args) throws Exception{
  // 1 创建BufferedInputStream
  FileOutputStream fos = new FileOutputStream("路径");
  BufferedOutputStream bis = new BufferedOutputStream(fos);
  // 2 写入文件
  for(int i = 0; i < 10; i ++){
    bos.write("hello".getBytes());// 写入8k缓冲区
    bos.flush(); // 刷新到硬盘
  }
  // 3 关闭
  bos.close();
}