I have an InputStream which I would like to convert to a PDF, and save that PDF in a directory. Currently, my code is able to convert the InputStream to a PDF and the PDF does show up in the correct directory. However, when I try to open it, the file is damaged.
Here is the current code:
InputStream pAdESStream = signingServiceConnector.getDirectClient().getPAdES(this.statusReader.getStatusResponse().getpAdESUrl());
byte[] buffer = new byte[pAdESStream.available()];
pAdESStream.read(buffer);
File targetFile = new File(System.getProperty("user.dir") + "targetFile2.pdf");
OutputStream outStream = new FileOutputStream(targetFile);
outStream.write(buffer);
Originally, the InputStream was a pAdES-file (https://en.wikipedia.org/wiki/PAdES). However, it should be able to be read as just a regular PDF.
Does anyone know how to convert the InputStream to a PDF, without getting a damaged PDF as a result?
available(). To read a stream completely, you should generally loop untilread()returns -1. There are various third party libraries to simplify this, but fundamentally it's not terribly hard... typically you read into a buffer, copying into aByteArrayOutputStream. Alternatively, if you're just copying the stream to a file, just loop reading from your input stream and writing to the file.InputStreamimplementations which return the full file size byavailable, in particular theFileInputStream. Most others merely return the bytes already fetched and residing e.g. in some buffer.