package com.io_.inputstream_;
import org.junit.Test;
import java.io.FileInputStream;
import java.io.IOException;
public class FileInputStream_ {
public static void main(String[] args) {
/*
* InputStream:字节输入流
* InputStream抽象类是所有类字节输入流的超类
* InputStream 常用的子类
* 1. FileInputStream : 文件输入流(字节 文件--> 程序)
* 2. BufferedInputStream: 缓冲字节输入流
* 3. ObjectInputStream: 对象字节输入流
*/
}
//1. FileInputStream : 文件输入流(字节 文件--> 程序)
// read() 单个字节的读取,效率比较低
//1. 先定义一个读取文件的方法
@Test
public void readFile01() {
//2. 读取文件的路径
String filePath = "e:\\hello.txt";
//3. 通过创建对象的方法 new FileInputStream() 用于读取文件 filePath
int read = 0; //判断读取完毕
FileInputStream fileInputStream = null; //扩大fileInputStream 的作用域 ,方便后面关闭文件流
try {
fileInputStream = new FileInputStream(filePath); // try/catch/finally捕获异常
//4. 用read() 方法读取 (单个字节的读取)
//从该输入流读取一个字节(用 while 循环来一直读取)的数据,如果没有输入可用,此方法将阻止
//如果返回-1 表示读取完毕
while ((read = fileInputStream.read()) !=-1) {
System.out.print((char) read); //read()返回的是int类型,要转成 char
}
} catch (IOException e) {
e.printStackTrace();
} finally {
//5. 关闭文件流,释放资源
try {
fileInputStream.close(); //try/catch 捕获关闭文件流的异常
} catch (IOException e) {
e.printStackTrace();
}
}
}
// read(byte[] b) 读取文件,提高效率
@Test
public void readFile02() {
String filePath = "e:\\hello.txt";
FileInputStream fileInputStream = null;
// 定义一个字符数组
byte[] buf = new byte[8]; //一次读取8个字符
//byte[] buf = new byte[1024] 里面一般写的是1024的整数倍
//定义读取的长度
int readLen = 0;
try {
fileInputStream = new FileInputStream(filePath);
//从该输入流读取最多b.length字节的数据到字节数组。此方法将阻塞,直到某些输入可用
//如果返回-1,表示读取完毕
//如果读取正常,返回实际读取的字节数
while (( readLen = fileInputStream.read(buf)) !=-1){
System.out.print(new String(buf,0,readLen));// 将byte[] 数组类型转成 String 类型输出文件数据 将读取到的字符从0 到 readLen 转换
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
fileInputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
版权声明:本文为l1341886243原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。