java - 有没有一种方法可以在不使用 byte[ ] 或 readAllBytes() 的情况下使用 java 1.8 读取 PDF 文件流
问题描述
我的要求是调用一个 Rest api,它的 o/p 是一个 pdf 文件并使用基于 java 的脚本语言生成一个 PDF 文件。我们在脚本中使用 readAllBytes() 方法,因为我们不能在脚本中使用 byte[](限制)。下面是我们脚本的等效 java 代码。由于不推荐使用 readAllBytes() 方法来读取大流,是否有不使用 byte[] 的替代方法?.
请注意:我们使用的是 1.8 java,不能使用除 Apache Commons IO 之外的任何第三方库。
谢谢您的帮助。
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedWriter;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
public class ExecuteReportFromScript {
public static void main(String[] args) {
// TODO Auto-generated method stub
try {
byte[] buffer = new byte[1024];
URL url = new URL("restEndPoint");
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("GET");
con.setRequestProperty("Cookie", "myCookieData");
con.setRequestProperty("Accept", "application/json");
con.setDoOutput(true);
con.connect();
System.out.println("Response Code:" + con.getResponseCode());
InputStream ip = con.getInputStream();
BufferedInputStream is = new BufferedInputStream(ip);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
bos.write( is.readAllBytes());
/*
* int length; while ((length = is.read(buffer)) > -1 ) { bos.write(buffer, 0,
* length); }
*/
bos.flush();
File file = new File("PathToFile\\FileName.pdf");
try(BufferedOutputStream salida = new BufferedOutputStream(new FileOutputStream(file))){
salida.write(bos.toByteArray());
salida.flush();
}
ip.close();
is.close();
bos.close();
} catch (MalformedURLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
解决方案
使用(自 Java 7)将流直接写入文件。Files.copy(InputStream in, Path target, CopyOption... options)
Path file = Paths.get("PathToFile\\FileName.pdf");
try (InputStream in = new BufferedInputStream(con.getInputStream())) {
Files.copy(in, file);
}
推荐阅读
- amazon-dynamodb - 提供的关键元素与架构不匹配 - updateItem
- html - 如何在内容和内容上使用不透明度::之前不重叠
- google-sheets - 计数范围内的行是否设置了两个条件
- apache-spark - spark xml:需要结构类型但得到字符串;
- ms-access - 使用 Ms Access LEFT JOIN 获取以前的余额作为欠款
- scala - Scala拆分序列或按分隔符列出
- vba - 收到错误“ByRef 参数类型不匹配”
- excel - 如何计算我单击形状的次数?
- android - 如何将回收站视图的全部内容刷新为默认值,包括它们所在的图标,但当前位置除外
- ios - 为什么我得到未定义的符号_OBJC_CLASS_$_FIRInstanceID?