2

I have a query that is in the below code i have a file name as shown below

String filename = "C:\\abcd\\Ttre.xls";

which later on i am passing to FileInputStream object as shown below

FileInputStream fileStream = new FileInputStream(filename);
workbook = new HSSFWorkbook(fileStream);

the happy case above was that filename was hardcoded which was pass to the FileInputStream object but lets say if some one is giving me file in form of byte array then how to deal with that case for example as shown below

public void abcd( byte[] excelByteStream) {
    //how to pass the the byte array file to the FileInputStream object 
}

so in that case how we would pass the bytestream file to the FileInputStream object please advise

3
  • What is HSSFWorkbook? Can in handle an InputStream in its constructor or does it specifically need a FileInputStream? Commented Jul 12, 2015 at 6:19
  • @SkinnyJ it can also , i have shown the explicit one can you show please how we can pass the input stream in it's constructor also Commented Jul 12, 2015 at 6:20
  • docs.oracle.com/javase/7/docs/api/java/io/… Commented Jul 12, 2015 at 6:25

2 Answers 2

2

You can't. FileInputStream is a type of InputStream that expects a file as input.

To use a byte array, you would use java.io.ByteArrayInputStream, which is also another type of InputStream.

Just make sure that whatever is expecting an input stream is defined to accept the more generic InputStream. (e.g.: public HSSFWorkbook(InputStream inputStream) { // HSSFWorkbook constructor definition)

Documentation: ByteArrayInputStream.

EDIT: A more complete example

If your HSSFWorkbook class has the constructor currently defined as:

public HSSFWorkbook(FileInputStream inputStream) {
    // ...
}

... you would want to change it to accept the more generic InputStream class, which would now allow you to pass it either a FileInputStream or a ByteArrayInputStream instance depending on where you call it from. Like this:

public HSSFWorkbook(InputStream inputStream) {
    // ...
}

Then you can instantiate your HSSFWorkbook using either option:

FileInputStream fileStream = new FileInputStream(filename);
workbook = new HSSFWorkbook(fileStream); // still works

... or ...

ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(excelByteStream);
    workbook = new HSSFWorkbook(byteArrayInputStream ); // now also works.
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks can you also please correct my above posted code that will help to grasp more Thanks in advance
1

Use ByteArrayInputStream instead of FileInputStream:

workbook = new HSSFWorkbook(excelByteStream);

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.