FileInputStream读取数据

24 篇文章 0 订阅

package cn.itcast_02;

import java.io.FileInputStream;
import java.io.IOException;

/*
* 字节输入流操作步骤:
* A:创建字节输入流对象
* B:调用read()方法读取数据,并把数据显示在控制台
* C:释放资源
*
* 读取数据的方式:
* A:int read():一次读取一个字节
* B:int read(byte[] b):一次读取一个字节数组
*/
public class FileInputStreamDemo {
public static void main(String[] args) throws IOException {
// FileInputStream(String name)
// FileInputStream fis = new FileInputStream(“fis.txt”);
FileInputStream fis = new FileInputStream(“FileOutputStreamDemo.java”);

// // 调用read()方法读取数据,并把数据显示在控制台
// // 第一次读取
// int by = fis.read();
// System.out.println(by); //97
// System.out.println((char) by); //a
//
// // 第二次读取
// by = fis.read(); //类似迭代器的next()方法 接着上一次往下读
// System.out.println(by); //98
// System.out.println((char) by); //b
//
// // 第三次读取
// by = fis.read();
// System.out.println(by); //99
// System.out.println((char) by); //c
// // 我们发现代码的重复度很高,所以我们要用循环改进
// // 而用循环,最麻烦的事情是如何控制循环判断条件呢?
// // 第四次读取
// by = fis.read();
// System.out.println(by); //-1
// // 第五次读取
// by = fis.read();
// System.out.println(by); //-1
// //通过测试,我们知道如果你读取的数据是-1,就说明已经读取到文件的末尾了

// 用循环改进
// int by = fis.read();
// while (by != -1) {
// System.out.print((char) by);
// by = fis.read();
// }

// 最终版代码
int by = 0;
// 读取,赋值,判断
while ((by = fis.read()) != -1) {
System.out.print((char) by);
}

// 释放资源
fis.close();
}
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值