InputStream抽象类的三种实现

文件IO这块可能很多开发者没有涉及,平时的工作主要集中在CRUD的业务逻辑开发上,对于金融或者电信有些核心系统会大量使用文件IO。这里的文件主要是话单或者交易凭证,开发者需要读取这些文件,将文件的内容转为实体或者消息发送给其他的子系统去处理。大家常用的读取和写入文件的方式是用FileInputStream和FileOutputStream,本文将为大家带来另外两种文件读取的方式,让大家在写代码的时候有跟多的选择。
 InputStream是文件读取的抽象基类,java.io包下的文件读取都会直接或者间接实现这个抽象类,下面给出几个常用的文件读取的类关系图:

从类关系图上看到有FileInputStream,ByteArrayInputStream,FilterInputStream三个实现类,今天主要给大家讲解的是FileInputStream,ByteArrayInputStream和BufferedInputStream。

FileInputStream类上的注释非常简单:该类从文件系统的某个文件中获取输入字节。

 public static void main(String[] args) {
        FileInputStream fis = null;
        File file = new File("D:/test.txt");
        try {
            byte[] buf = new byte[16];
            int length = 0;
            fis = new FileInputStream(file);
            StringBuilder stringBuilder =new StringBuilder();
            while ((length=fis.read(buf))!=-1){
                stringBuilder.append(new String(buf, 0, length));
            }

            System.out.println(stringBuilder.toString());
        } catch (FileNotFoundException fnfe){
            System.out.println(fnfe);
        } catch (IOException ioe) {
            System.out.println(ioe);
        } finally {
            if(null != fis){
                try {
                    fis.close();
                } catch (IOException ioe){
                    System.out.println(ioe);
                }
            }
        }
 }

ByteArrayInputStream类上的注释说该类在内部维护了一个byte类型的数组,该数组起到缓冲区的作用,另外还有一个指向下一个要读字符的位置的索引。

public static void main(String[] args){
        String msg = "dalddngndaa";
        InputStream bis = new ByteArrayInputStream(msg.getBytes());
        int askCode = 0;
        try {
            while ((askCode=bis.read())!=-1){
                System.out.println((char)askCode);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
}

BufferedInputStream类的注释说在内部维护了一个buffer数组用来读入文件里的数据,额外提供了标记和重置的方法可以从缓存中取到上一次的数据。

public static void main(String[] args){
	InputStream bufis = new BufferedInputStream(fis);
	byte[] buffer = new byte[8];
	StringBuilder stringBuilder = new StringBuilder();
	try {
		while (bufis.read(buffer, 0, buffer.length)!=-1){
			for(int i=0; i<buffer.length; i++){
				stringBuilder.append((char)buffer[i]);
			}

			System.out.println(stringBuilder.toString());
		}
	} catch (IOException e) {
		e.printStackTrace();
	}
}

本文对三种不同的输入流的用法做了详细的介绍,在使用上推荐使用BufferedInputStream,速度上比前两种更快。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值