[英]Is there a way to read PDF file stream with out using byte[ ] or readAllBytes() using java 1.8
My requirement is to invoke a Rest api, the o/p of which is a pdf file & generate a PDF file using a scripting language which is based on java. 我们在脚本中使用 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();
}
}
使用 Files.copy Files.copy(InputStream in, Path target, CopyOption... options)
将 stream 直接写入文件(自 Java 7 起) 。
Path file = Paths.get("PathToFile\\FileName.pdf");
try (InputStream in = new BufferedInputStream(con.getInputStream())) {
Files.copy(in, file);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.