字节输入流读取字节数据和字节输入流一次读取多个字节
读取数据的原理(硬盘-->内存)
java程序-->JVM-->OS-->OS读取数据的方法-->读取文件
字节输入流的使用步骤:
1.创建FileInputStream对象,构造方法中绑定要读取的数据源
2.使用FileInputStream对象中的方法read,读取文件
3.释放资源
package com.yang.Test.IOStudy;
import java.io.FileInputStream;
import java.io.IOException;
public class InStudy01 {
public static void main(String[] args) throws IOException {
FileInputStream in = new FileInputStream("Document\\1.txt");
int read = in.read();
System.out.println(read);//97 a
read = in.read();
System.out.println(read);//98 b
read = in.read();
System.out.println(read);//99 c
//int read()读取文件中的一个字节并且返回,读取到文件末尾返回-1
read = in.read();
System.out.println(read);//-1
/**
* 发现以上读取文件是一个重复的过程,所以可以使用循环优化
* 不知道文件中有多少字节,使用while循环
* while循环结束条件,读取到-1的使用结束
*/
int len = 0;
while ((len = in.read()) != -1) {
System.out.println((char) len);
}
in.close();
}
}
字节输入流一次读取多个字节
package com.yang.Test.IOStudy;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Arrays;
/**
* 字节输入流一次读取多个字节的方法:
* int read(byte b)从输入流中读取一定数量的字节,并将其存储在缓冲区数组b中。
* 明确两件事情:
* 1.方法的参数byte[]的作用?
* 2.方法的返回值int是什么?
*
* String类的构造方法
* String(byte[] bytes):把字节数组转换为字符串
* String(byte[] bytes,int offset,int length)把字节数组的一部分转换为字符串 offset:数组的开始索引,length:转换的字节个数
*/
public class InStudy01 {
public static void main(String[] args) throws IOException {
//创建FileInputStream对象,构造方法中绑定要读取的数据源
FileInputStream in = new FileInputStream("Document\\bbb.txt");
//使用FileInputStream对象中的read读取文件
//int read(byte[] b)从输入流中读取一定数量的字节,并将其存储在缓冲区数组b中
byte[] bytes = new byte[2];
int read = in.read(bytes);
System.out.println(read);//2
System.out.println(Arrays.toString(bytes));//[112, 97]
System.out.println(new String(bytes));//pa
in.close();
}
}
分类:
java基础+进阶
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构