欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Java的IO流技术——文件字节流

程序员文章站 2022-10-03 17:43:17
一、FileInputStream/FileOutputStream使用 FileInputStream 读取文件内容1)int read() :从此输入流中读取一个数据字节。2)int read(byte[] b) :从此输入流中将最多 b.length 个字节的数据读入一个 byte 数组中。3)int read(byte[] b, int off, int len) :从此输入流中的off位置将最多 len个字节的数据读入一个byte 数组中。4)int available() :从此输入...

一、FileInputStream/FileOutputStream

使用 FileInputStream 读取文件内容

1)int read() :从此输入流中读取一个数据字节。

2)int read(byte[] b) :从此输入流中将最多 b.length 个字节的数据读入一个 byte 数组中。

3)int read(byte[] b, int off, int len) :从此输入流中的off位置将最多 len个字节的数据读入一个byte 数组中。

4)int available() :从此输入流估计剩余字节数。

5)void close() :关闭此文件输入流并释放与此流有关的所有系统资源

例子:

public class TestInpuStream {
    public static void main(String[] args) throws IOException {
        //数据源与应用程序之间搭建管道
        FileInputStream fis = new FileInputStream("D:/test.txt");
        //估算输入流剩余字节数
        int count = fis.available();
        System.out.println("估算输入流剩余字节数是:"+count);
        //一次读取一个字节
        //System.out.println(fis.read());
        //利用循环读取多个字节
        //int buf1 = 0;
        //while((buf1 = fis.read()) != -1){
        //    System.out.print((char)buf1);
        //}
        //利用数组读取多个字节
        byte[] buf2 = new byte[1024];
        int len = 0;        //存储每次读到的实际字节
        System.out.println("读取到的内容是:");
        while((len = fis.read(buf2)) != -1){
            System.out.println(new String(buf2,0,len));
        }
        //关闭
        fis.close();
    }
}

运行结果:
Java的IO流技术——文件字节流
使用 FileOutputStream 写内容到文件

1)void write(int b) :将指定字节写入此文件输出流。

2)void write(byte[] b) :将 b.length 个字节从指定 byte 数组写入此文件输出流中。

3)void write(byte[] b, int off, int len) :将指定 byte 数组中从偏移量 off 开始的 len 个字节写入此文件输出流。

4)void flush() :清空数据缓冲区。

5)void close() :关闭此文件输出流并释放与此流有关的所有系统资源。

例子:

public class Main {
    public static void main(String[] args) {
        //搭桥
        FileOutputStream fos = null;
        try {
            /* true 如果磁盘上有文件并且文件中有内容
                   则将在原来的内容的基础上进行追加 */
            fos = new FileOutputStream("D:/a.txt",true);
            //一次写一个字节
            //fos.write(97);
            //一次写多个字节
            byte[] buf = "hello world".getBytes();
            fos.write(buf);;
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if(fos != null){
                    fos.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

运行结果:
Java的IO流技术——文件字节流

本文地址:https://blog.csdn.net/m0_46294535/article/details/107660272