2

I am trying to import xls sheet to DB, for that when i am uploading the file the uploaded file is in ByteBuffer Format, i have written a logic which reads as FileInputStream.

Now how do i convert this ByteBuffer to FileInputStream

Here is my Code

        ByteBuffer fileBytes = (ByteBuffer) context.get("uploadedFile");
        String encoding = System.getProperty("file.encoding");
        String filename = Charset.forName(encoding).decode(fileBytes).toString();
        filename = filename.replaceAll("\\r", "");

I tried Casting it using ByteArrayInputStream() but looks like it is not working!

Raghu Chandra
  • 1,102
  • 1
  • 9
  • 14

1 Answers1

4
  1. Change your logic to use InputStream rather than FileInputStream. You don't care where the input comes from.
  2. Use the following code:

    ByteArrayInputStream bais = new ByteArrayInputStream(buffer.array(), buffer.position(), buffer.limit());
    

and pass bais to your existing method.

user207421
  • 305,947
  • 44
  • 307
  • 483
  • Looks like file is getting passed properly but apache poi is not able to read it i think! I am getting this error java.io.IOException: Unable to read entire header; 0 bytes read; expected 512 bytes – Raghu Chandra Mar 12 '15 at 08:20
  • It's not much use telling us about an error message without posting the entire stack trace and showing us which line of code threw it. Yout haven't posted the code for your 'logic', but it is almost infinitely more likely that the bug is in there rather than in the one-liner I've posted above. – user207421 Mar 12 '15 at 09:00
  • Thanks EJP! the problem is fixed now! doing just **new ByteArrayInputStream(fileBytes.array());** would work fine in excel import case! PS: posted this as this may help some other searching for soln... – Raghu Chandra Mar 12 '15 at 10:28
  • That's not the code I provided, and it won't work in the general case. If you found this answer useful you should consider upvoting or accepting it, or both. That will also help others searching for a solution. – user207421 Mar 12 '15 at 10:33