Search code examples
javarestfileinputstream

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. We are using readAllBytes() method in our scripts, as we cannot use byte[] in our scripts(restriction). Equivalent java code for our script is below. As using readAllBytes() method is not recommended for reading large streams, is there an alternative for this without using byte[]? .

Please note: We are using 1.8 java and cannot use any third party libraries except Apache Commons IO.

Thank you for your help.


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();
     }

 } 

Solution

  • Write the stream directly to a file using Files.copy(InputStream in, Path target, CopyOption... options) (since Java 7).

    Path file = Paths.get("PathToFile\\FileName.pdf");
    try (InputStream in = new BufferedInputStream(con.getInputStream())) {
        Files.copy(in, file);
    }