有没有办法使用 java 1.8

问题描述

我的要求是调用一个 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,* 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();
     }

 } 

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)