IO读数据
IO读数据
基础的读取
- 创建字节输入流对象
- 将字节数据从硬盘中输入至内存以达到读取数据
- 会被抛来异常,可以选择抛出或者try-catch处理
- 调用read()方法将指定字节写入此文件输出流中
- 所有流最后都要释放资源
import java.io.FileInputStream;
import java.io.IOException;
public class Demo1 {
public static void main(String[] args) throws IOException {
// new一个FileInputStream类对象
// java.txt内容为ab,只有两个值
FileInputStream fileInputStream = new FileInputStream("java基础\\src\\com\\io\\read\\base\\java.txt");
// 使用读数据的read()方法
// 只能一个一个读
// 输出结果为97
// System.out.println(fileInputStream.read());
// 转成字符型
// 输入结果为a
// System.out.println((char)fileInputStream.read());
// // 第二次读
// // 输出结果为b
// System.out.println((char) fileInputStream.read());
// // 第三次读
// // 输出结果为-1
// System.out.println(fileInputStream.read());
// // 第四次读
// // 输出结果为-1
// System.out.println(fileInputStream.read());
// 此时想到可以写成循环
// 没有读到末尾就循环读
// int read = fileInputStream.read();
// while (read != -1) {
// // 每一次循环读数据
// System.out.print((char)read);
// // 每一次循环赋值判断条件
// read = fileInputStream.read();
// }
// 我们还能对上述代码进行优化
// 定义一个变量,用于判断条件
int read;
// 每次读取并赋值给变量,并进行判断
// 融合了上述判断和结尾赋值
while ((read = fileInputStream.read()) != -1 ){
// 输出读取
System.out.print((char)read);
}
// 释放资源
fileInputStream.close();
}
}
一次读一个字节数组数据
// 定义一个长度为1024及其整数倍的字节数组
byte[] bytes = new byte[1024];
int read;
while ((read = fileInputStream.read(bytes)) != -1){
System.out.println(new String(bytes,0, read));
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构