Java IO字节流

🧭Java IO流学习
🎉 内容回顾
Java IO流介绍及文件操作
📢今天我们进行Java IO字节流的学习,感谢你的阅读,内容若有不当之处,希望大家多多指正,一起进步!!!
♨️如果觉得博主文章还不错,可以👍三连支持⭐一下哦😀

Java IO字节流

字节流

字节流介绍

一切文件(文本、图片、视频)在存储时,都是以 二进制 的形式存储的,都可以通过使用字节流传输。

字节流顶层抽象类

InputStream:字节输入流超类
OutputStream:字节输出流超类

字节流传输的单位是 字节 8bit
InputStreamOutputStream都属于字节流的超类,他们是抽象类,不能直接使用,需要用他们相应的子类来实例化,在Java API中所有以这两个类为后缀的类均属于字节流
例如:FileInputStream、FileOutputStream分别属于文件字节输入流 文件字节输出流

字节输入流InputStream

public abstract class InputStream implements Closeable

字节输入流超类 InputStream实现了Closeable接口,Closeable 是可以关闭的数据源或目标。调用 close 方法可释放对象保存的资源(如打开文件)。

该类提供了核心方法:

1. 每次读取一个字节的数据,为int类型,读取到文件末尾的时候返回 -1

public abstract int read() throws IOException;

2. 每次读取的数据存到字节数组中,返回读取到的有效字节的个数,读取到文件末尾的时候返回 -1

public int read(byte b[]) throws IOException

3. 每次读取数据到字节数组中,从偏移位置off开始,长度为len,返回结果是读取到的有效字节的个数,读取到文件末尾的时候返回 -1

public int read(byte b[], int off, int len) throws IOException 

FileInputStream

以实现类FileInputStream为例介绍读取文件的字节输入流

构造函数

FileInpustream构造函数主要有

public FileInputStream(String name) throws FileNotFoundException 
public FileInputStream(File file) throws FileNotFoundException 

当传入的文件不存在的时候,运行会抛出FileNotFoundException异常。

read方法

以读取电脑上a.txt文件为例,路径为:"e:\Java\a.txt"
在这里插入图片描述
1. int read() 每次读取一个字节,返回结果表示读取的数据int类型值,数据读取到结尾返回 -1
代码示例:

@Test
    public void fileInputStreamTest01 () {
        String filePath = "e:\\Java\\a.txt";
        FileInputStream fis = null;

        try {
            fis = new FileInputStream(filePath);//打开流
           //读取文件,读到文件末尾返回-1
            int read = 0;
            while((read = fis.read()) != -1) {
                System.out.print((char)read);
            }

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally { //关闭流,释放资源
            if (fis != null) {
                try {
                    fis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

运行结果:
在这里插入图片描述
2. int read(byte b[]) 将数据读取到byte数组,返回结果表示读取的数据个数,数据读取到结尾返回 -1
使用数组读取,每次可以读取多个字节,减少了系统间的IO操作次数,从而提高效率, 【建议使用】

代码示例:

@Test
    public void fileInputStreamTest02 () {
        String filePath = "e:\\Java\\a.txt";
        FileInputStream fis = null;

        try {
            fis = new FileInputStream(filePath);//打开流

            byte[] bytes = new byte[2];//把读取到的字节存储到该数组
            int readLength = 0;//每次读取到的字节个数
            while((readLength = fis.read(bytes)) != -1) { //读取文件,读到文件末尾返回-1
                System.out.print(new String(bytes,0,readLength));
            }

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally { //关闭流,释放资源
            if (fis != null) {
                try {
                    fis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

运行结果: 在这里插入图片描述
🚀【补充】
int read(byte b[]) 底层读取机制,每次读取数组个长度字节到数组中,读取的过程其实是覆盖数组原来数据的过程。
以上述代码的为例,其读取过程为:
在这里插入图片描述
最后一次读不到两个,只能读取一个。所以打印结果用的是new String(bytes,0,readLength)

3. int read(byte b[], int off, int len) 将数据读取到byte数组,从byte数组的off位置偏移,最多偏移len位置 len = b.length 返回结果表示读取的数据个数,读取到结尾返回 -1

代码示例:

    @Test
    public void fileInputStreamTest03 () {
        String filePath = "e:\\Java\\a.txt";
        FileInputStream fis = null;

        try {
            fis = new FileInputStream(filePath);//打开流

            byte[] bytes = new byte[4];//把读取到的字节存储到该数组
            int readLength = 0;//每次读取到的字节个数
            while((readLength = fis.read(bytes,0,bytes.length)) != -1) { //读取文件,读到文件末尾返回-1
                System.out.print(new String(bytes,0,readLength));
            }

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally { //关闭流,释放资源
            if (fis != null) {
                try {
                    fis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

运行结果:
在这里插入图片描述

字节输出流OutputStream

public abstract class OutputStream implements Closeable, Flushable

字节输出流超类 OutputStream实现了Closeable接口和Flushable接口,Closeable 是可以关闭的数据源或目标。调用 close 方法可释放对象保存的资源(如打开文件)。Flushable是可以刷新的数据的目的地。 调用flush方法将任何缓冲输出写入到依赖的流

该类提供了核心方法:

1. 将int值写入到输出流中

public abstract void write(int b) throws IOException; 

2. 将字节数组从偏移量off开始,写入len个长度到输出流

public void write(byte b[], int off, int len) throws IOException;

3. 刷新输出流并强制缓冲字节被写出

public void flush() throws IOException 

FileOutputStream

以实现类FileOutputStream为例介绍文件的字节输出流

构造函数
FileOutputStream主要是向磁盘文件中写入数据,常用构造方法如下
在这里插入图片描述
🚀【注意】
● 上述构造方法执行后,如果file不存在,会自动创建该文件
● 如果file存在,append没有传或者传了false,会清空文件的数据
● 如果file存在,append传了true,不会清空文件的数据

write方法
以往电脑上b.txt文件写入数据为例,路径为:"e:\Java\b.txt"
在这里插入图片描述

1. void write(int b) 写入一个int类型的字符
代码示例:

    @Test
    public void fileOutputStreamTest01() {
        FileOutputStream fos = null;
        String filePath = "e:\\Java\\b.txt";

        try {
            fos = new FileOutputStream(filePath);//打开流
            fos.write('a');//往b.txt文件中写入 a
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally { //关闭流,释放资源
            if (fos != null) {
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

运行结果:
在这里插入图片描述
2. write(byte[] ) 写入一个byte类型的数组
代码示例:

    @Test
    public void fileOutputStreamTest02() {
        FileOutputStream fos = null;
        String filePath = "e:\\Java\\b.txt";

        try {
            fos = new FileOutputStream(filePath);//打开流
            byte[] chars = {'h', 'e', 'l', 'l', 'o'};
            fos.write(chars);//往b.txt文件中写入 写入数组
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally { //关闭流,释放资源
            if (fos != null) {
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

运行结果:
在这里插入图片描述
3. write(byte[],int off,int len) 写入一个byte类型的数组并指定其中的内容

 @Test
    public void fileOutputStreamTest03() {
        FileOutputStream fos = null;
        String filePath = "e:\\Java\\b.txt";

        try {
            fos = new FileOutputStream(filePath);//打开流
            byte[] chars = {'h', 'e', 'l', 'l', 'o'};
            fos.write(chars,1,3);//往b.txt文件中写入chars数组中的第二个到第四个数据
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally { //关闭流,释放资源
            if (fos != null) {
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

运行结果:
在这里插入图片描述

文件拷贝

【文件拷贝】 把电脑 “e:\Java\study.jpg” 复制到 “e:\Java\a\study.jpg”
在这里插入图片描述
代码示例:

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * @author wyscoder
 * @version 1.0
 */
public class FileCopy {
    public static void main(String[] args) {
        String sourceFilePath = "e:\\Java\\study.jpg";
        String descpath = "e:\\Java\\a\\study.jpg";
        copyFile(sourceFilePath,descpath);
    }

    /**
     * 拷贝文件
     * @param sourceFilePath 原文件路径
     * @param descPath 目标文件路径
     */
    public static void copyFile(String sourceFilePath, String descPath) {
        FileInputStream fis = null;
        FileOutputStream fos = null;

        try {
            fis = new FileInputStream(sourceFilePath);//打开字节输入流
            fos = new FileOutputStream(descPath);//打开字节输出流

            byte[] buff = new byte[1024];//把数据读到buff数组中
            int readLength = 0; //读取到数据长度
            while((readLength = fis.read(buff)) != -1) {//边读边写
                fos.write(buff,0,readLength);
            }
            System.out.println("拷贝成功~~~");
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {//关闭流,释放资源
            try {
                if (fis != null) {
                    fis.close();
                }
                if (fos != null) {
                    fos.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

运行结果:
在这里插入图片描述
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

WYSCODER

你的鼓励将是我创作的最大动力

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

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

打赏作者

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

抵扣说明:

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

余额充值