美文网首页
初学Java,IO流中FileInputStream采用byte

初学Java,IO流中FileInputStream采用byte

作者: 石头时代zy | 来源:发表于2020-04-17 07:47 被阅读0次

    IO流中FileInputStream采用byte[]方式读取。
    相比单纯使用read()方法读取文件,采用byte[]方式读取占用资源较少,一次读取的量较大,也就是read(byte b[])。
    声明byte[]时采用静态初始化,这里让他每次读8byte
    输出时使用String(byte bytes[], int offset, int length)的方式输出,length就是最终read(byte b[])的返回值。offset一般从第0个下标开始读取,所以是String(bytes,0,readback)

    import java.io.FileInputStream;
    import java.io.FileNotFoundException;
    import java.io.IOException;
    
    public class Test{
        public static void main(String[] args) {
            //声明FileInputStream并赋值null
            FileInputStream fileInputStream = null;
            try {
                //newFileInputStream,可以使用绝对路径,也可以使用相对路径
                // 相对路径在工程下开始
                fileInputStream = new FileInputStream("文件路径");
                //采取byte数组形式读取,每次读8byte
                byte[] bytes = new byte[8];
                //声明一个readback来取回读取到的字节数
                int readback;
                //while循环当readback取回-1时break
                while((readback = (fileInputStream.read(bytes))) != -1){
                    System.out.print(new String(bytes,0,readback));
                }
                //异常的处理
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                //关闭FileInputStream流(必要)
                try {
                      if (fileInputStream != null) {
                        fileInputStream.close();
                      }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
    

    相关文章

      网友评论

          本文标题:初学Java,IO流中FileInputStream采用byte

          本文链接:https://www.haomeiwen.com/subject/dhalvhtx.html