muhammed aslam
muhammed aslam

Reputation: 44

how to convert an input stream to a file

I have a web program which reads data from excel and insert it into database.

I am reading it from jsp as parts and then convert it into input stream.

    Part filePart = request.getPart("file");
    InputStream fileContent = filePart.getInputStream();

Then the below code is used to create a work book(org.apache.poi.ss.usermodel.Workbook) from it

    Workbook wb = null;
    Sheet sheet = null;
    try {
        wb = WorkbookFactory.create(fileContent);
        sheet = wb.getSheetAt(0);
    } catch (InvalidFormatException | EncryptedDocumentException | NullPointerException ex) {
        return null;
    }

from here I found this

create

public static Workbook create(java.io.InputStream inp)

Creates the appropriate HSSFWorkbook / XSSFWorkbook from the given InputStream.

Note that using an InputStream has a higher memory footprint than using a File.

So is there any way to convert an InputStream to File

or Parts to File

Thanks....

Upvotes: 0

Views: 10586

Answers (1)

Michael Akerman
Michael Akerman

Reputation: 329

Try FileUtils from Apache Commons IO

Part filePart = request.getPart("file");
InputStream fileContent = filePart.getInputStream();
File tempFile = File.createTempFile( "myfile", ".xls" )
FileUtils.copyToFile( fileContent, tempFile );

You'd also need:

import org.apache.commons.io.FileUtils;

And the appropriate dependency if you're using Maven:

<dependency>
    <groupId>commons-io</groupId>
    <artifactId>commons-io</artifactId>
    <version>2.6</version>
</dependency>

Upvotes: 1

Related Questions