java基础--IO流
参考
javaguide
缓存解决流重复读取
mark和rest解决流重复读取SF
Java POI重复读取excel
IO流种类
- 流的方向:输入流和输出流
- 操作单元:字符流和字节流
- 流的角色:字节流和处理流
IO流
- InputStream/Reader: 所有的输入流的基类,前者是字节输入流,后者是字符输入流。
- OutputStream/Writer: 所有输出流的基类,前者是字节输出流,后者是字符输出流。
输入流 InputStream 不可以重复读取
InputStream就类比成一个杯子,杯子里的水就像InputStream里的数据,你把杯子里的水拿出来了,杯子的水就没有了,InputStream也是同样的道理。
重复读取的方法
- 直接重新获取(有时候不一定能重新获取)
InputStream inputStream = new FileInputStream(path);
//利用inputStream
inputStream = new FileInputStream(path);
//再次利用inputStream
- 过ByteArrayOutputStream,以缓存的方式去处理(占用内存)
public static byte[] streamToData(InputStream uristream) {
ByteArrayOutputStream outStream = null;
try {
outStream = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len = 0;
while ((len = uristream.read(buffer)) != -1) {
outStream.write(buffer, 0, len);
}
return outStream.toByteArray();
} catch (Exception e) {
return null;
} finally {
try {
if (uristream != null) {
uristream.close();
}
if (outStream != null) {
outStream.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
//把需要复用的inputStream保存为data
byte[] data = streamToData(inputstream);
//复用
InputStream in1 = new ByteArrayInputStream(data);
InputStream in2 = new ByteArrayInputStream(data);
- 通过mark()和reset()方法,以标记和重置的方式实现(不是所有的inputStream支持,需要先判断是否支持)
inputStream.markSupported()
5.读取部分,使用回退流。如poi读取excel时。参考文章 Java POI重复读取excel
==========================end==================
菜鸟也想飞的更高