import java.io.FileInputStream;
import java.io.IOException;
public class InputStream {
public static void main(String[] args) {
//要求读取E盘上的file01文件 内容输出到控制台上
InputStream i=new InputStream();
i.readFile();
System.out.println();
i.readFile01();
}
public void readFile(){
//单个字节的读取
String Filepath="e:/file01.txt";
int read=0;
FileInputStream fis= null;
try {
fis = new FileInputStream(Filepath);
while((read= fis.read())!=-1){
//读出来的是文本文件中对应的字节本身 比如 a---->97
//如果为-1 则文件读取完成
System.out.print((char)read);
}
} catch (IOException e) {
e.printStackTrace();
}finally {
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
//定义字节数组提高读取效率
public void readFile01(){
String Filepath="e:/file01.txt";
int read=0;
byte by[]=new byte[8];
FileInputStream fis= null;
try {
fis = new FileInputStream(Filepath);
//此处read返回的是读取的字节长度
while((read= fis.read(by))!=-1){
//read(byte[n])方法一次读取n个长度的字节
// 比如txt中有一个字符串“abcd” n=4时可以一次性读取到定义的数组中
System.out.print((new String(by,0,read)));
//从下标为offset开始 读了多少个就转化成多少个
}
} catch (IOException e) {
e.printStackTrace();
}finally {
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
Read方法:
将文本文件中的字符按字节一次读出 输出-1时 读取完毕
while循环一次性读取
提高效率: 预先设定一个字节长度的数组 就相当于一个缓冲
一次性读取设定长度的字节数