InputStream在使用完后,不关闭流,想复用怎么办?

1.以ByteArrayInputStream为例

先看代码

package test;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;

public class Test {
	public static void main(String[] args) {
		String content = "MengUer";
		InputStream inputStream = new ByteArrayInputStream(content.getBytes());
		int ch;
		try {
			while ((ch = inputStream.read()) != -1) {
				System.out.print((char) ch);
			}
		} catch (IOException e) {
			e.printStackTrace();
		}

		System.out.println("\n" + "-------华丽的分割线------");

		try {
			// 注意!
			inputStream.reset();
			while ((ch = inputStream.read()) != -1) {
				System.out.print((char) ch);
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}

运行结果如下:

MengUer
-------华丽的分割线------

MengUer

如果没有inputStream.reset()方法,结果是这样的:

MengUer
-------华丽的分割线------

1.1说一下InputStream中的三个方法

mark(int readlimit)

public synchronized void mark(int readlimit) {}

在流的readlimit处标记。

默认为空。

reset()

public synchronized void reset() throws IOException {
        throw new IOException("mark/reset not supported");
    }

从被标记的地方开始读。

默认抛出异常。

markSupported()

public boolean markSupported() {
        return false;
    }

判断是否支持标记。

默认不支持。

1.2该类复写了上述的三个方法

protected int mark = 0;
public void mark(int readAheadLimit) {
        mark = pos;
    }

public synchronized void reset() {
        pos = mark;
    }

public boolean markSupported() {
        return true;
    }

其中mark默认为0,也就是说只要你调用reset方法,程序就会把流完整的再读一遍。如果你想从流中特定的地方开始读,要重新设置mark值。

2.以FileInputStream为例

import org.apache.commons.io.FileUtils;

File file = new File("xx.jpg");
try {
	if (picInputStream == null) {
		//处理
	}
	FileUtils.copyToFile(picInputStream, file);
	// 因为以上方法会自动关闭输入流,所以要重新开启
	picInputStream = Files.newInputStream(file.toPath());
} catch (Exception e) {
	e.printStackTrace();
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值