I'm trying to get a copy of the content from the stream without consuming it. My plan is to use this original stream in the later of the code. Following is the sample code I tried to check this. My intention is to keep the original InputStream for future use after getting a copy
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
public class StreamTest {
public static void main(String[] args) {
try {
InputStream inputstream = new FileInputStream("resource.txt"); // content of the file is 'test'
ByteArrayOutputStream baos = new ByteArrayOutputStream();
org.apache.commons.io.IOUtils.copy(inputstream, baos);
byte[] bytes = baos.toByteArray();
System.out.println("copied stream : " + new String(bytes));
StringBuilder sb = new StringBuilder();
BufferedReader br = new BufferedReader(new InputStreamReader(inputstream));
String line;
while ((line = br.readLine()) != null) {
sb.append(line + System.lineSeparator());
}
System.out.println("original stream : " + sb.toString());
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
but still, when I access the original stream, after coping it, I still see that the original stream is consumed. See below output
copied stream : test
original stream :
Can someone point out my mistake
Thanks