gpt4 book ai didi

java - 从输入流读取数据时出现 SocketException [ byte[] bytes = toByteArray(input) ]

转载 作者:行者123 更新时间:2023-12-01 16:39:48 25 4
gpt4 key购买 nike

问题:

在开发一个实用程序以将多个 pdf 流合并到单个输出流时,我在从输入流列表中的输入流中读取数据时收到SocketException,即在这一行 [ byte[] bytes = toByteArray(input) ]。这会导致仅来自某些输入流的数据被合并到单个 pdf 中,并且少数引发异常的输入流不会被合并。

注意:下面代码中 inputStreamList 中的输入流是通过在各个 URL 上调用 openStream() 方法创建的。

此错误仅有时在少数环境而非所有环境中发生。这些环境托管在不同的服务器上。

代码块:

public void doMergeIntoFile(List<InputStream> inputStreamList, final String fileName) throws IOException {
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
PDFMergerUtility merger = new PDFMergerUtility();
merger.setDestinationStream(outputStream);
merger.setDocumentMergeMode(OPTIMIZE_RESOURCES_MODE);
for (InputStream input : inputStreamList) {
try {
byte[] bytes = toByteArray(input); // gives Socket exception sometimes
PDDocument.load(bytes).close();
merger.addSource(new ByteArrayInputStream(bytes));
} catch (IOException ioExcep) {
log.error("An exception was encountered while parsing input stream : {0}", ioExcep);
continue;
}
}
merger.mergeDocuments(setupMainMemoryOnly());
outputStream.flush();
outputStream.close();
generatePdf(outputStream.toByteArray(), fileName);
}
}

异常消息:

ERROR [origo.bimta.web.action.pdf.PDFAction] (default task-27) An exception was encountered while parsing input stream : {0}: java.net.SocketException: Connection reset
at java.net.SocketInputStream.read(SocketInputStream.java:210)
at java.net.SocketInputStream.read(SocketInputStream.java:141)
at java.io.BufferedInputStream.fill(BufferedInputStream.java:246)
at java.io.BufferedInputStream.read1(BufferedInputStream.java:286)
at java.io.BufferedInputStream.read(BufferedInputStream.java:345)
at sun.net.www.MeteredStream.read(MeteredStream.java:134)
at java.io.FilterInputStream.read(FilterInputStream.java:133)
at sun.net.www.protocol.http.HttpURLConnection$HttpInputStream.read(HttpURLConnection.java:3393)
at sun.net.www.protocol.http.HttpURLConnection$HttpInputStream.read(HttpURLConnection.java:3386)
at com.google.common.io.ByteStreams.copy(ByteStreams.java:207)
at com.google.common.io.ByteStreams.toByteArray(ByteStreams.java:252)
at origo.bimta.web.action.pdf.PDFAction.doMergeIntoFile(PDFAction.java:482)

请求解决方案:

有人可以建议一种方法来解决此问题,以便可以防止此套接字异常,或者一种方法可以使输入流列表中的所有输入流都能成功读取并最终成功合并到单个 pdf 中吗?

最佳答案

为什么要转换为字节数组?您应该直接使用 inputstream 。

for (InputStream input : inputStreamList) {
try {
merger.addSource(input);
} catch (IOException ioExcep) {
log.error("An exception was encountered while parsing input stream : {0}", ioExcep);
}
}

关于java - 从输入流读取数据时出现 SocketException [ byte[] bytes = toByteArray(input) ],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61883081/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com