How to convert InputStream to virtual File

Something like this should work. Note that for simplicity, I’ve used a Java 7 feature (try block with closeable resource), and IOUtils from Apache commons-io. If you can’t use those it’ll be a little longer, but the same idea. import org.apache.commons.io.IOUtils; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; public class StreamUtil { public static … Read more

FileNotFoundException while getting the InputStream object from HttpURLConnection

I don’t know about your Spring/JAXB combination, but the average REST webservice won’t return a response body on POST/PUT, just a response status. You’d like to determine it instead of the body. Replace InputStream response = con.getInputStream(); by int status = con.getResponseCode(); All available status codes and their meaning are available in the HTTP spec, … Read more

How to Cache InputStream for Multiple Use

you can decorate InputStream being passed to POIFSFileSystem with a version that when close() is called it respond with reset(): class ResetOnCloseInputStream extends InputStream { private final InputStream decorated; public ResetOnCloseInputStream(InputStream anInputStream) { if (!anInputStream.markSupported()) { throw new IllegalArgumentException(“marking not supported”); } anInputStream.mark( 1 << 24); // magic constant: BEWARE decorated = anInputStream; } @Override … Read more

How do I convert an OutputStream to an InputStream?

There seem to be many links and other such stuff, but no actual code using pipes. The advantage of using java.io.PipedInputStream and java.io.PipedOutputStream is that there is no additional consumption of memory. ByteArrayOutputStream.toByteArray() returns a copy of the original buffer, so that means that whatever you have in memory, you now have two copies of … Read more

Most efficient way to create InputStream from OutputStream

If you don’t want to copy all of the data into an in-memory buffer all at once then you’re going to have to have your code that uses the OutputStream (the producer) and the code that uses the InputStream (the consumer) either alternate in the same thread, or operate concurrently in two separate threads. Having … Read more

Reading a binary input stream into a single byte array in Java

The simplest approach IMO is to use Guava and its ByteStreams class: byte[] bytes = ByteStreams.toByteArray(in); Or for a file: byte[] bytes = Files.toByteArray(file); Alternatively (if you didn’t want to use Guava), you could create a ByteArrayOutputStream, and repeatedly read into a byte array and write into the ByteArrayOutputStream (letting that handle resizing), then call … Read more