InputStream字节输入流
1.InputStream字节输入流
- InputStream抽象类是所有类字节输入流的超类;
- FileInputStream:文件输入流
- BufferedInputStream:缓冲字节输入流
- ObjectInputStream:对象字节输入流
1.InputStream关系图
2.FileInputStream 读取文件
单个字节读取,效率比较低,如果读取的是中文,会乱码,因为UTF-8一个中文等于3个字节,这里是一个一个读取的,肯定会乱码
@Test
public void readFile01(){
String filePath = "d:\\news1.txt";
int readData = 0;
//用于读取文件
FileInputStream fileInputStream = null;
try {
//用于读取文件
fileInputStream = new FileInputStream(filePath);
//从该输入流读取一个字节的数据,如果没有输入可用,此方法将阻止
//如果返回-1,表示读取完毕
while ((readData = fileInputStream.read())!=-1){
//转成char显示
System.out.print((char)readData);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
//关闭文件流,释放资源
try {
fileInputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
使用read(byte[] byte)读取,提高效率
@Test
public void readFile02(){
String filePath = "d:/111.txt";
int readLen = 0;
//字节数组,一次读取1024个字节,可自定义
byte[] buf = new byte[1024];
//用于读取文件
try(FileInputStream fileInputStream = new FileInputStream(filePath)){
//从该输入流读取一个字节的数据,如果没有输入可用,此方法将阻止
//如果返回-1,表示读取完毕
//如果读取正常,返回实际读取的字节数
while ((readLen = fileInputStream.read(buf))!=-1){
//转成char显示
System.out.println(new String(buf,0,readLen));
}
}catch (IOException e) {
e.printStackTrace();
}
}