InputStream 简介

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

public class InputStreamDemo {
   /*
    * InputStream字节输入流
    * FileInputStream:文件字节输入流
    * --->构造方法
    * 1.new FileInputStream(File file):
    *   传入File对象,代表了文件源
    * 2.new FileInputStream(String name):
    *   传入String类型的文件路径,该路径代表的文件是文件源。
    */
   
   public static void main(String[] args)  {
      File file = new File("D:/test/a.txt");
      InputStream is = null;
      try {
         is=    new FileInputStream(file);
      
      /*
       * int|read():一次一个字节,返回int  Unicode编码表
       */
      /*int i = is.read();
      System.out.println(i);
   */
      /*
       * int | read(byte[] bytes):把读取到的内容存入byte数组中,
       * 返回值为每次读取到的字节的个数。如果不存在则返回-1
       */
   /* String str = "";
      int len = 0;
      byte[] bytes = new byte[3];
      while((len = is.read(bytes)) != -1){//还有剩余内容
         //System.out.println(Arrays.toString(bytes));
         String s = new String(bytes,0,len);
         str += s;
      }
      System.out.println(str);
      */
      /*
       * int | read(byte[] bytes , int off,int len):
       * 把读取到的内容存入bytes数组中,每次从下标为off开始
       * 最多存储len个,返回值为每次读取到的字节的个数。
       * 如果读取不到内容则返回-1
       */
      byte[] bytes = new byte[3];
      String str = "";
      int len = 0;
      while((len = is.read(bytes, 1, 2)) != -1){
         String s = new String(bytes,1,len);
         str += s;
      }
      System.out.println(str);
      
      } catch (IOException e) {
         e.printStackTrace();
      }finally{
         if(is != null){
            try {
               is.close();
            } catch (IOException e) {
               e.printStackTrace();
            }
         }
      }
   }
}

猜你喜欢

转载自blog.csdn.net/Peter_S/article/details/86614470