java - 执行操作后在 InputStream 中丢失内容
问题描述
我正在使用外部扫描工具执行数据检查。在此过程中,我将 InputStream 传递给扫描工具。该工具扫描流并以布尔值响应。使用这个布尔值,我将决定是否要将流保存到文件中。在此过程中,该工具不会重置输入流,而是处于 EOF 状态。这使它无法使用。因此我创建的文件将有 0 字节。
我无法更改执行此操作的工具。所以我需要找到一种不影响 InputStream 内容的方法。但同时执行输入流的扫描和写入。
这是我的代码,
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
}
在上面的代码片段中,
if (!scanTool.scan(IOUtils.toByteArray(httpcon.getInputStream()))) {
// exit with fail code
}
这是我的新插入。我正在调用 scanTool 来执行检查条件的操作,只有当它通过时才继续写入文件。现在,在执行此操作时,我丢失了 inputStream 中的内容。
我在这里想念什么。我什至尝试使用 BufferedInputSteam。还是不行。还尝试了另一种方法,我构造新的可读字节通道,然后从中构造新的 InputStream。如注释代码所示。但没有果实。
解决方案
鉴于您已经将 InputStream 转换为 byte[],您可以在扫描后写出相同的字节数组:
byte[] bytes = IOUtils.toByteArray(httpcon.getInputStream());
if (!scanTool.scan(bytes)) {
// exit with fail code
}
try(FileOutputStream fos = new FileOutputStream(filePath)) {
fos.write(bytes);
}
推荐阅读
- python - 清理时间戳数据 - Python
- android - 加密用户数据而不会丢失 android 应用程序中的登录用户
- ajax - 如何使用ajax将选择框和文本值从搜索表单传递到控制器?
- javascript - 有没有办法根据对话结果将信息从 Microsoft 聊天机器人发送到网站
- sql-server-2012 - 从 SQL Server 中具有相等条件的表中选择
- java - ForkJoinPool 性能 Java 8 与 11
- php - 有没有办法在 laravel 模型中访问自己的关系属性?
- java - 使用 Selenium Java 进行屏幕捕获时显示新窗口
- selenium-webdriver - 我们能否编写一个以元素为参数并返回结果的泛型方法。(例如返回 isDisplayed() 函数结果的方法)?
- mysql - MySQL 其中 datediff 等于某个值