Search code examples
javaio

Is it possible to create a File object from InputStream


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.


Solution

  • 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.