Java IO——字节流常用类介绍&实战演示

字节输入流


我们首先来看输入流。

InputStream

InputStream是字节输入流的抽象基类,实现了读取的基本操作。

  • read(byte[])

从流中读取b的长度个字节的数据存储到b中,返回结果是读取的字节个数。

    public int read(byte b[]) throws IOException {
        return read(b, 0, b.length);
    }
  • read(byte[], int, int)

从off的位置开始读取len个字节的数据存储到b中,返回结果是实际读取到的字节个数。

    public int read(byte b[], int off, int len) throws IOException {
        ……
        return i;
    }
  • close()
    public void close() throws IOException {}

关闭流,释放资源,每次流操作之后必须要调用它。

FileInputStream

主要方法

FileInputStream主要用来操作文件输入流,它除了可以使用基类定义的函数外,它还实现了基类的read()函数(无参的)。

    public int read() throws IOException {
        // Android-changed: Read methods delegate to read(byte[], int, int) to share Android logic.
        byte[] b = new byte[1];
        return (read(b, 0, 1) != -1) ? b[0] & 0xff : -1;
    }

可以看到,read()从字节流中,只读取了一个字节。

示例代码:
    /**
     * 文件字节流读取
     * @param fileName
     */
    public static void fileIO(String fileName){
        File file = new File(fileName);
        FileInputStream fileInputStream = null;
        try {
            fileInputStream = new FileInputStream(file);
            byte[] bytes = new byte[100];
            int length = -1;
            StringBuilder str = new StringBuilder();
            while ((length = fileInputStream.read(bytes)) != -1) {
                str.append(new String(bytes, 0, length));
            }
            Log.d("budaye", "str = " + str);
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            try {
                fileInputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

BufferedInputStream

BufferedInputStream 是缓冲输入流,它继承于FilterInputStream。

BufferedInputStream增加了缓存功能,我们在之前的《Java IO——字节流和字符流详解&区别对比》中知道,字节流操作默认没有缓存功能,是直接从存储设备中读取,每一个字节操作都需要一次IO。BufferedInputStream可以避免频繁的IO操作,提高了字节流操作的性能和效率。

BufferedInputStream的作用是为其它输入流提供缓冲功能,通常在创建BufferedInputStream时,我们会通过它的构造函数指定某个输入流为参数。BufferedInputStream会将该输入流数据分批读取,每次读取一部分到缓冲中;操作完缓冲中的这部分数据之后,再从输入流中读取下一部分的数据。

主要方法

它实现了基类的read()函数(无参的):

    public synchronized int read() throws IOException {
        if (pos >= count) {
            fill();
            if (pos >= count)
                return -1;
        }
        return getBufIfOpen()[pos++] & 0xff;
    }

read():从流中读取1个字节的数据,返回结果是一个int。

示例代码:
    public static void bufferedInput(String fileName) {
        File file = new File(fileName);
        FileInputStream fileInputStream = null;
        InputStream in = null;
        try {
            fileInputStream = new FileInputStream(file);
            in = new BufferedInputStream(fileInputStream);//以输入流作为参数
            byte[] bytes = new byte[1024];
            int length = -1;
            StringBuilder str = new StringBuilder();
            while ((length = in.read(bytes)) != -1) {
                str.append(new String(bytes, 0, length));
            }
            Log.d("budaye", "str = " + str);
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            try {
                in.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

字节输出流


输出流与输入流相对应。

OutputStream

OutputStream是字节输出流的抽象基类,它与InputStream对应,实现了字节流输出的的基本操作。

  • write(int b)
    public abstract void write(int b) throws IOException;

将b字节数据写到输出流中,需要在子类中实现。

  • write(byte b[])
    public void write(byte b[]) throws IOException {
        write(b, 0, b.length);
    }

将b的长度个字节数据写到输出流中。

  • write(byte b[], int off, int len)

从b的off位置开始,获取len个字节数据,写到输出流中。

  • flush()
    public void flush() throws IOException {
    }

刷新输出流,把数据马上写到输出流中,需要在子类中复写。

  • close()
    public void close() throws IOException {
    }

关闭流,释放系统资源,需要在子类中复写。

FileOutputStream

FileOutputStream用于写文件的输出流,它除了可以使用基类定义的函数外,还实现了OutputStream的抽象函数write(int b)。

主要方法

实现了OutputStream的抽象函数write(int b),将制定的字节数据写入到文件输出流。

    public void write(int b) throws IOException {
        // Android-changed: Write methods delegate to write(byte[],int,int) to share Android logic.
        write(new byte[] { (byte) b }, 0, 1);
    }
    
        public void write(byte b[], int off, int len) throws IOException {
        // Android-added: close() check before I/O.
        if (closed && len > 0) {
            throw new IOException("Stream Closed");
        }

        // Android-added: Tracking of unbuffered I/O.
        tracker.trackIo(len);

        // Android-changed: Use IoBridge instead of calling native method.
        IoBridge.write(fd, b, off, len);
    }
示例代码:
    public static void outputToFile(String fileName){
        File f = new File(fileName);
        OutputStream out = null;
        try {
            out = new FileOutputStream(f);//如果文件不存在会自动创建
            String str = "Hello World";
            byte[] b = str.getBytes();
            for (int i = 0; i < b.length; i++) {
                out.write(b[i]);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            try {
                out.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

BufferedOutputStream

与BufferedInputStream对应,是缓冲输入流,它继承于FilterOutputStream。

主要方法
  • 它实现了OutputStream的抽象函数write(int b)方法。
    public synchronized void write(int b) throws IOException {
        if (count >= buf.length) {
            flushBuffer();
        }
        buf[count++] = (byte)b;//将数据b直接写入缓存数组。
    }
  • 它的close方法继承父类FilterOutputStream的close方法:
    //这里使用了try-resource的方式关闭流,同时调用flush方法,确保数据已经写出。
    public void close() throws IOException {
        try (OutputStream ostream = out) {
            flush();
        }
    }
示例代码:
    public static void outputBufferedToFile(String fileName){
        File f = new File(fileName);
        FileOutputStream out = null;
        BufferedOutputStream buff = null;
        try {
            out = new FileOutputStream(f, true);//向文件末尾添加
            buff = new BufferedOutputStream(out);
            String str = "outputBufferedToFile";
            byte[] b = str.getBytes();
            buff.write(b);
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            try {
                buff.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

卜大爷

觉得不错的可以给我加油哦

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值