2.1.IO流-输入流

FileInputStrem 文件字节输入流

用于读取文本、图片、音乐、视频等文件数据

构造方法:

  • 传入文件路径:public FileInputStream(String name)
  • 传入File 对象:public FileInputStream(File file)
  • public FileInputStream(FileDescriptor fdObj)

通过其 read() 方法,每次读取一个字节,返回 -1 结束

read()方法返回的类型为 int,直接输出返回值,得到的只是数字。需要转换为char字符

常规步骤

  1. 声 明 流:FileInputStream in = null;
  2. 初始化流:in = new FileInputStream(filePath);
  3. 读取数据:while循环,read方法,-1停止
  4. 关 闭 流:in.close();

单个字符读取

// 声明FileInputStream对象
FileInputStream in = null;
try {
    // 初始化流
    String filePath = "C:/Users/BigBanana/Desktop/projects/fileDir/test.txt";
    in = new FileInputStream(filePath);

    // 循环读取文件字节
    int b;
    while (true) {
        b = in.read();
        // 读到字节为-1时,结束
        if (b == -1) {
            break;
        }
        // 输出字节
        System.out.print((char) b);
    }
} catch (IOException e) {
    e.printStackTrace();
} finally {
    // 判断 流 不为空。关闭
    if (in != null) {
        try {
            in.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

批量字符读取

// 声明FileInputStream对象
FileInputStream in = null;
try {
    // 初始化流
    String filePath = "C:/Users/BigBanana/Desktop/projects/fileDir/test.txt";
    in = new FileInputStream(filePath);

    // 字节数组
    byte[] bytes = new byte[4];
    // 循环批量读取文件字节
    int length;
    while (true) {
        length = in.read(bytes);
        // 读到字节为-1时,结束
        if (length == -1) {
            break;
        }
        // 输出字节
        System.out.print(new String(bytes,0,length));
    }

} catch (IOException e) {
    e.printStackTrace();
} finally {
    // 判断 流 不为空。关闭
    if (in != null) {
        try {
            in.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值