Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert InputStream to virtual File

I have a method which expects the one of the input variable to be of java.io.File type but what I get is only InputStream. Also, I cannot change the signature of the method.

How can I convert the InputStream into File type with out actually writing the file on to the filesystem?

like image 834
Ram Avatar asked Nov 30 '10 18:11

Ram


People also ask

How do you convert an InputStream into String in Java?

To convert an InputStream Object int to a String using this method. Instantiate the Scanner class by passing your InputStream object as parameter. Read each line from this Scanner using the nextLine() method and append it to a StringBuffer object. Finally convert the StringBuffer to String using the toString() method.

How do I get BufferedReader from InputStream?

The BufferedReader can't read the InputStream directly; So, we need to use an adapter like InputStreamReader to convert bytes to characters format. For example: // BufferedReader -> InputStreamReader -> InputStream BufferedReader br = new BufferedReader( new InputStreamReader(inputStream, StandardCharsets. UTF_8));


2 Answers

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 final String PREFIX = "stream2file";     public static final String SUFFIX = ".tmp";      public static File stream2file (InputStream in) throws IOException {         final File tempFile = File.createTempFile(PREFIX, SUFFIX);         tempFile.deleteOnExit();         try (FileOutputStream out = new FileOutputStream(tempFile)) {             IOUtils.copy(in, out);         }         return tempFile;     }  } 
like image 159
cobbzilla Avatar answered Sep 20 '22 10:09

cobbzilla


You can't. The input stream is just a generic stream of data and there is no guarantee that it actually originates from a File. If someone created an InputStream from reading a web service or just converted a String into an InputStream, there would be no way to link this to a file. So the only thing you can do is actually write data from the stream to a temporary file (e.g. using the File.createTempFile method) and feed this file into your method.

like image 45
Jan Thomä Avatar answered Sep 23 '22 10:09

Jan Thomä