InputStream和BufferedInputStream类详解
InputStream抽象类,我们找它的一个子类对它进行分析。FileInputStream类。测试文件为大写的A到Z的txt文件。
available方法可以查看该文件的字符数,也可以分析该输入流后面还有多少字符可以输入。
read方法可以每次读一个文件中的字符,以int的值返回。测试如下:
public static void main(String[] args) throws IOException {
InputStream fis = new FileInputStream("C:\\Users\\RedTea\\Desktop\\iotest.txt");
System.out.println(fis.read());
System.out.println(fis.available());
fis.close();
}//测试结果为:65 25 //65也就是A所对应的ASCII值
在使用完IO流后,一定要记住将其关闭。也就是调用close方法。否则会占用系统资源,或者造成其他意想不到的事情。。。
read方法除了读一个字节的int外,还可以一次性读一个byte数组的内容,并将它们放在byte数组中。如下:
public static void main(String[] args) throws IOException {
InputStream fis = new FileInputStream("C:\\Users\\RedTea\\Desktop\\iotest.txt");
byte [] b=new byte[5];
fis.read(b);
fis.close();
System.out.println(b[0]);
System.out.println(b[4]);
//测试结果为:65 69说明一次读了5个byte
read方法中的参数类型还可以是read(byte[],int,int),其中byte[]是数据保存的数组,两个int分别是数据保存的初始位置以及要保存多少个数据。测试如下:
public static void main(String[] args) throws IOException {
InputStream fis = new FileInputStream("C:\\Users\\RedTea\\Desktop\\iotest.txt");
byte [] b=new byte[5];
fis.read(b,2,3);
fis.close();
for(int a:b){
System.out.println(a);
}
}//测试结果为:0 0 65 66 67
markSupported方法可以测试InputStream的子类们是否支持mark和reset方法。而FileInputStream返回的是false。
skip方法可以让你跳过输入流的n个字节。
public static void main(String[] args) throws IOException {
InputStream fis = new FileInputStream("C:\\Users\\RedTea\\Desktop\\iotest.txt");
System.out.println(fis.markSupported());
System.out.println(fis.read());
fis.skip(1);
System.out.println(fis.read());
fis.close();
}//测试结果为:false 65 67
BufferInputStream类,这个类是InputStream类的子类FilterInputStream的子类。这货支持mark方法和reset方法,在读字符流的时候会创建一个牛逼的缓冲区,这个缓冲区减少了对字符操作的开销。效率较直接用InputStream高。其他方法基本和InputStream类似,测试代码如下:
public static void main(String[] args) throws IOException {
InputStream ins =new FileInputStream("C:\\Users\\RedTea\\Desktop\\iotest.txt");
BufferedInputStream bis = new BufferedInputStream(ins);
bis.mark(1);
System.out.println(bis.read());
System.out.println(bis.read());
bis.reset();
System.out.println(bis.read());
ins.close();
bis.close();
}//测试结果为:65 66 65
这回我用的是一个24K大一点的txt文件,效率测试如下:
public static void main(String[] args) throws IOException {
long pre =System.currentTimeMillis();
InputStream ins =new FileInputStream("C:\\Users\\RedTea\\Desktop\\iotest.txt");
BufferedInputStream bis = new BufferedInputStream(ins);
while(bis.available()!=0){
bis.read();
}
long post =System.currentTimeMillis();
System.out.println(post-pre+"*******");
}
}//测试结果为:31*******
如果直接用FileInputStream中的read方法,测试代码如下:
public static void main(String[] args) throws IOException {
long pre =System.currentTimeMillis();
InputStream ins =new FileInputStream("C:\\Users\\RedTea\\Desktop\\iotest.txt");
while(ins.available()!=0){
ins.read();
}
ins.close();
long post =System.currentTimeMillis();
System.out.println(post-pre+"*******");
}
}//测试结果为:63*******
每次运行得到的结果可能不一样,但用不用Buffered所用的时间就在31周围和63周围波动,由此可见BufferedInputStream类的效率较InputStream是狠高的。。。