黑马程序员_字节流

字符流:
FileReader
FileWriter
BufferedFileReader
BufferedFileWriter

字节流:
字节流不需要flush,但是仍然需要关闭流资源。
FileInputStream
FileOutputStream
BufferedInputStream
BufferedOutputStream

注意:单个字节读取时read()返回int实际上是在读取的byte上补位;write(int)实际上是把int的最低8位写入。

FileOutputStream:
write()方法接收byte数组,所以用字符串的getBytes()方法将String转成数组:
 public static void writeFile() throws IOException
  {
    FileOutputStream fos = new FileOutputStream("x.txt");
    fos.write("abcde.kihdsa\r\nsdhasdasd\r\n{}HH".getBytes()); //字符串转byte数组
    fos.close();
  }


FileInputStream:
三种读取方式:
1)单个字节读取
public static void readFile_1() throws IOException
  {
    FileInputStream fis = new FileInputStream("x.txt");
    int num = 0;
    while((num = fis.read()) != -1)
      System.out.print((char)num);    //打印在屏幕上,所以转为char
    fis.close();
  }

2)字节数组读取
  public static void readFile_2() throws IOException
  {
    FileInputStream fis = new FileInputStream("x.txt");
    byte[] b = new byte[1024];
    int num = 0;
    while((num = fis.read(b)) != -1)
      System.out.print(new String(b,0,num));
    fis.close();
  }

3)还是字节数组读取,但是用available()方法直接获取数组长度【使用时注意内存溢出问题】
  public static void readFile_3() throws IOException
  {
    FileInputStream fis = new FileInputStream("x.txt");
    byte[] b = new byte[fis.available()];
    fis.read(b);
    System.out.print(new String(b));
    fis.close();
  }
}

BufferedInputStream
可以装饰InputStream类,自己写一个MyBufferedInputStream类:
import java.io.*;

class MyBufferedInputStream
{
  private InputStream in;
  private byte[] buf = new byte[1024];
  private pos = 0,count = 0;

  MyBufferedInputStream(InputStream in)
  {
    this.in = in;
  }

  public int myRead() throws IOException
  {
    if(count == 0)
    {
      count = in.read(buf);
      if(count < 0)
        return -1;
      pos = 0;
      byte b = buf[pos];

      count--;
      pos++;

      return b&0xff;  //byte转换成int缺位补0,以免11111111变成-1(11111111 11111111 11111111 11111111),而非255(00000000 00000000 00000000 11111111)
    }
    else if(count > 0)
    {
      byte b = buf[pos];

      count--;
      pos++;

      return b&0xff; //byte转换成int缺位补0,以免11111111变成-1(11111111 11111111 11111111 11111111),而非255(00000000 00000000 00000000 11111111)
    }
    return -1;
  }

  public void myClose() throws IOException
  {
    in.close();
  }
}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值