使用FileInputStream和ByteArrayOutputStream 实现文本数据的回读

1、使用context.openFileInput(fileName)方法打开当前应用下的files文件夹下的fileName文件,这里所指向的txt文本中存入了文本“hello world!”。

2、使用inputStream.read(buffer)方法分段的把txt文本中的内容写入buffer数组。

      这里为buffer数组指定了长度为3,所以“hello world!”这组长度为11的数据会被分成4次写入到buffer数组中。

      其中Log.i("len", String.valueOf(len));把每次循环执行时len的值写入到LogCat中,分别为3、3、3、2。

      当inputStream.read(buffer)把数据都写入到buffer数组之后,它最后还会返回一次len为-1的值,代表数据完全读完。

3、使用outStream.write(buffer, 0, len)方法,在while循环体内把每次写入到buffer数组的值再次叠加写入到内存缓冲区中。

4、使用outStream.toByteArray()方法把内存缓冲区中的数据流转换成字节数组。

5、最后把字符数组转换成字符串进行返回return new String(data)。

	public String read(String fileName) throws Exception {
		int len = 0;
		FileInputStream inputStream = context.openFileInput(fileName);
		ByteArrayOutputStream outStream = new ByteArrayOutputStream();
		byte [] buffer = new byte[3];
		while( (len = inputStream.read(buffer)) != -1){
			Log.i("len", String.valueOf(len));
			outStream.write(buffer, 0, len);
		}
		byte [] data = outStream.toByteArray();
		return new String(data);
	}

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值