I am performing data check using an external scan tool. In the process I pass the InputStream into the scan tool. The tool scans the stream and respond back with a boolean value. Using this boolean value I will decide If I would want to save the stream to a file or not. During the process the tool will not reset the inputstream, and it will be left in a EOF-state. Which makes it unusable. And hence the file I am creating will have 0 Bytes.
There is no way I can alter the tool that is doing this. So I would need to find out a way not to affect the InputStream content. But at the same time perform scan and writing of the Input Stream.
Here is my code,
FileOutputStream fos = null;
ReadableByteChannel rbc = null;
try {
log.info(masterId + " : DOWNLOADING FILE FROM [ " + url + " ]");
HttpURLConnection httpcon = (HttpURLConnection) urlConnection;
//rbc = Channels.newChannel(httpcon.getInputStream()); -- this was my another approach
//InputStream inputStream = Channels.newInputStream(rbc);
if (!scanTool.scan(IOUtils.toByteArray(httpcon.getInputStream()))) {
// exit with fail code
}
rbc = Channels.newChannel(httpcon.getInputStream());
fos = new FileOutputStream(filePath);
fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);
fos.close();
rbc.close();
return 1;
} catch (FileNotFoundException ex) {
//Handle exception
}
In the above code snippet,
if (!scanTool.scan(IOUtils.toByteArray(httpcon.getInputStream()))) {
// exit with fail code
}
This is my new insertion. I am calling the scanTool to perform an operation to check a condition, only if it passes then go ahead and write the file. Now while doing this I am losing the content in the inputStream.
What am i missing here. I even tried using BufferedInputSteam. Still not working out. also tried the another approach where I construct new readable byte channel and then construct new InputStream out of it. As shown in the commented code. But no fruit.
question from:
https://stackoverflow.com/questions/65847446/losing-content-in-inputstream-after-performing-operation 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…