Is it possible to create a File object from InputStream

androidgalaxyman picture androidgalaxyman · Jul 16, 2012 · Viewed 173k times · Source

Is there any way to create a java.io.File object from an java.io.InputStream ?

My requirement is reading the File from a RAR . I am not trying to write a temporary File, I have a file inside RAR archive which I am trying to read.

Answer

Tomasz Nurkiewicz picture Tomasz Nurkiewicz · Jul 16, 2012

You need to create new file and copy contents from InputStream to that file:

File file = //...
try(OutputStream outputStream = new FileOutputStream(file)){
    IOUtils.copy(inputStream, outputStream);
} catch (FileNotFoundException e) {
    // handle exception here
} catch (IOException e) {
    // handle exception here
}

I am using convenient IOUtils.copy() to avoid manual copying of streams. Also it has built-in buffering.