FileInputStrem 文件字节输入流
用于读取文本、图片、音乐、视频等文件数据
构造方法:
- 传入文件路径:public FileInputStream(String name)
- 传入File 对象:public FileInputStream(File file)
- public FileInputStream(FileDescriptor fdObj)
通过其 read() 方法,每次读取一个字节,返回 -1 结束
read()方法返回的类型为 int,直接输出返回值,得到的只是数字。需要转换为char字符
常规步骤
- 声 明 流:FileInputStream in = null;
- 初始化流:in = new FileInputStream(filePath);
- 读取数据:while循环,read方法,-1停止
- 关 闭 流: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();
}
}
}