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();
}