V.Aggarwal
V.Aggarwal

Reputation: 563

Java : Convert an Inputstream string into file

I am trying to write a String (read from an InputStream) into a file. But when the output.pdf file is generated, it is corrupted.

In real-world scenario, I am receiving a string as an input from another service, from which I need to creat a file. Hence, created a test code like below

import org.apache.commons.io.IOUtils;
import org.apache.commons.io.FileUtils;


File inFile = new File("test_input.pdf");
File outFile = new File("output.pdf");
InputStream inputStream = FileUtils.openInputStream(inFile);

// this String looks like:
// %PDF-1.4 ....

String s = IOUtils.toString(inputStream);

// Aim is to write the generated string as another file
// This is generating a corrupted file
FileUtils.writeByteArrayToFile(outFile, IOUtils.toByteArray(s));

Upvotes: -2

Views: 588

Answers (1)

k314159
k314159

Reputation: 11246

Assuming your InputStream has the contents of a valid PDF file, all you need is:

    Path outFile = Path.of("output.pdf");
    try (InputStream inputStream = Files.newInputStream(Path.of("test_input.pdf"))) {
        Files.copy(inputStream, outFile);
    }

These classes and methods are all standard Java API. There is no need to use any third-party library such as Apache.

The problem you were having was probably caused by the decoding of bytes from the input stream into a String followed by the encoding of the String into the bytes written to the file. This is not generally a lossless conversion, especially when the content is non-ASCII text. On the other hand, Files.copy transfers the content directly.

Upvotes: 4

Related Questions