读取字节的方式

来源:互联网 发布:男士补水 知乎 编辑:程序博客网 时间:2024/05/20 16:44

读取数据的方式:

InputStream

1、           一个字节一个字节的读:

 实例代码:

       File file=new File("E:\\TestMain.java");

     

      try {

        InputStream is=new FileInputStream(file);

       

        int data=-1;

        while((data=is.read())!=-1){

           System.out.print((char)data);

        }

        is.close();

      } catch (FileNotFoundException e) {

        e.printStackTrace();

      } catch (IOException e) {

        // TODO Auto-generatedcatch block

        e.printStackTrace();

      }

 

2、一段一段的读:

File file=new File("E:\\TestMain.java");

      byte[] bytes=new byte[100];

     

      try {

        InputStream is=new FileInputStream(file);

       

        int data=-1;

        while((data=is.read(bytes))!=-1){

           System.out.print(new String(bytes,0,data));

        }

       

        is.close();

      } catch (FileNotFoundException e) {

        e.printStackTrace();

      } catch (IOException e) {

        // TODO Auto-generatedcatch block

        e.printStackTrace();

      }

 

3、文件全部读取,知道文件长度。

   File file=new File("E:\\TestMain.java");

      byte[] bytes=new byte[(int)file.length()];

     

      try {

        InputStream is=new FileInputStream(file);

       

//      int data=-1;

//      while((data=is.read(bytes))!=-1){

//         System.out.print(new String(bytes,0,data));

//      }

        is.read(bytes);

        System.out.println(new String(bytes));

        is.close();

      } catch (FileNotFoundException e) {

        e.printStackTrace();

      } catch (IOException e) {

        // TODO Auto-generatedcatch block

        e.printStackTrace();

      }

     

   }

 

优缺点:

全部读取:效率高:但是byte数组要占内存,如果文件太大,则在new byte[]时要占用大量的内存,再说要将文件的长度转换为int型,如果文件太大,则int满足不了,不能转换。中文字符可以显示,因为它全部读取。