The difference between the three reads of InputStream

The difference between the three reads of InputStream

1.
The read method reads this stream one byte, and the returned int is the int representation of this byte. The
following is a code snippet. After testing, when the encoding of eclipse is gbk, the converted string does not need to go through Re-encode. If the encoding of eclipse is utf-8, the byte must be converted into a string and needs to be re-encoded into utf-8.

InputStream in = Test.class.getResourceAsStream("/tt.txt");
  byte[]tt=new byte[15];//测试用的事前知道有15个字节码
  while(in.available()!=0){

   for(int i=0;i<15;i++){
    tt[i]=(byte)in.read();
   }
  }
  String ttttt=new String(tt,"utf-8");
  System.out.println(ttttt);
  in.close();

2.read(byte[] b)
This method first specifies an array length, buffers the bytes in this stream into array b, and returns the number of bytes in this array. If the buffer is not full, then Returns the actual number of bytes, and returns -1 until the end

in = Test.class.getResourceAsStream("/tt.txt");
  byte [] tt=new byte[1024];
  int b;
  while((b=in.read(tt))!=-1){

   System.out.println(b);
  String tzt=new String(tt,"utf-8");


  System.out.println(tzt);

3.read(byte[] b, int off, int len)
This method actually calls the read() method multiple times

InputStream in = Test.class.getResourceAsStream("/tt.txt");
  //System.out.println(in.available());//此方法是返回这个流中有多少个字节数,可以把数组长度定为这个

  byte[]tt=new byte[in.available()];
  int z;
  while((z=in.read(tt, 0, tt.length))!=-1){
   System.out.println(new String(tt,"utf-8"));
  }

Guess you like

Origin blog.csdn.net/lb687/article/details/76573889
Recommended