how to get the inputStream from Workbook object in java - java

When I upload the file i am passing the inputstream to the workbook. Now I want to use this InputStream from workbook in another method like save where I save the file InputStream in to DB. Here is my code.
public void FileUpload(FileUploadEvent event) throws ParseException {
UploadedFile item = event.getUploadedFile();
Workbook workbook = org.apache.poi.ss.usermodel.WorkbookFactory.create(item.getInputStream());
}
Now I want to make Workbook object as instance variable and pass to another method like below.
public String save() throws SQLException, IOException{
fileId = dao.savefile(workbook,fileName);
}
In my savefile method
InputStream inptest= **workbook.getStream**
ps.setBinaryStream(2,fin,fin.available());
So inptest variable accepts InputStream which I wanted to get it from Workbook.

It sounds like what you are asking for is a way to use the InputStream for multiple purposes:
To create a Workbook object (which you're already doing)
To save the content of that InputStream somewhere else
Since reading from an InputStream is usually a one-time-only operation that cannot be repeated, then you can do the following:
Save the full content of the InputStream to a buffer.
Open two new InputStreams from the buffer.
Pass your InputStreams to your two methods.
Code might look like this:
public void FileUpload(FileUploadEvent event) throws ParseException {
UploadedFile item = event.getUploadedFile();
InputStream originalInputStream = item.getInputStream();
byte[] buffer = IOUtils.toByteArray(originalInputStream);
InputStream is1 = new ByteArrayInputStream(buffer);
InputStream is2 = new ByteArrayInputStream(buffer);
Workbook workbook = org.apache.poi.ss.usermodel.WorkbookFactory.create(is1);
}
InputStream inptest = is2;
ps.setBinaryStream(2,fin,fin.available());
Note: this uses Apache Commons IO library for IOUtils.

If you are trying to save the Workbook object to a file, there is a method write() which takes in an OutputStream. Saving to a file can then be accomplished by
FileOutputStream fos = new FileOutputStream("path/to/file/[filename]");
workbook.write(fos);
fos.close();

Related

Why does my code ( ZipOutputStream ) saves empty file in ZIP?

I have a simple code that is supposed to make txt file zipped, though txt file has some content, it's empty in a zip folder ( it has 89 bytes ( like buffer ) but all are just spaces.
The interesting part is that if I write
byte[] buffer = Files.readAllBytes(path);
my code is working.
I am new to java and would appreciate your help a lot. Because I trully don't understand what I am doing wroing.
public class Test {
public static void main(String[] args) throws IOException {
try (FileInputStream fis = new FileInputStream("C:\\Users\\10\\Desktop\\ds.txt");
ZipInputStream zis = new ZipInputStream(fis);
ZipOutputStream zos = new ZipOutputStream(Files.newOutputStream(Paths.get("C:\\Users\\10\\Desktop\\ds.zip")))) {
byte[] buffer = new byte[fis.available()];
zos.putNextEntry(new ZipEntry("ds.txt"));
zis.read(buffer);
zos.write(buffer);
zos.closeEntry();
}
Since the text file is not zipped yet, don't use a ZipInputStream to read it. Just use the FileInputStream, or even better the NIO.2 File API (you're using it already to create the ZipOutputStream but not to create the InputStream).
There is even a file system provider for the NIO.2 File API to read/ write to Zip files using the same API: https://docs.oracle.com/javase/7/docs/technotes/guides/io/fsp/zipfilesystemprovider.html (For Java 11+ the following module is required: https://docs.oracle.com/en/java/javase/11/docs/api/jdk.zipfs/module-summary.html)
Also make sure to use try-with-resources for the OutputStream as well, not just the InputStream, to properly close the stream in the finally block.

Modify a value and write JSON to a file

I am trying to modify a JSON and write the modified JSON to a file. But the output file to which JSON was written was empty.
{
"id": 4051,
"name": "menad",
"livelng": 77.389849,
"livelat": 28.6282231,
"creditBalance": 127,
"myCash": 10
}
I want to update "creditBalance" value and write the JSON to a new File.
private static void readJs(String path) throws IOException, JSONException {
File file = new File(path);
FileInputStream fis = new FileInputStream(file);
byte[] buffer = new byte[(int) file.length()];
fis.read(buffer);
String json = new String(buffer, StandardCharsets.UTF_8);
JSONObject jsonObject = new JSONObject(json);
jsonObject.put("creditBalance",78); // <- Updating a value
FileWriter fw = new FileWriter("output.json");
fw.write(jsonObject.toString());
}
You lacked close filewriter:
fw.close();
It have to close
You can either:
Call the flush() method on your FileWriter object, which will cause it to actually write out the contents of its buffer, or
Call the close() method to close the FileWriter, which will cause it to flush automatically before closing.
Option 2 is the best choice if you are finished writing to this particular file. You should always be careful to close resources (like files) when you've completed operating on them.

Read excel file byte array

byte[] test = getByteArry(excelfikepath)
I have one method where it returns the bytearray of the excel .xlsx file. To read this file i need to write these byte array using FileOutputStream on one server and from there i am calling another method which will read and process that excel from the server.
There is some limitation because of which i cant read excel file directly i have to put it onto another server and process.
Just wanted to know is there any way by which i can make use of this byte array and read excel file IN MEMORY instead of writing it on server.
This will help to get byte array out of an excel file.
public static byte[] getFileByteArr(String fileName) throws InvalidFormatException, IOException {
try (OPCPackage opcPackage = OPCPackage.open(new File(fileName))) {
try (XSSFWorkbook workbook = (XSSFWorkbook) WorkbookFactory.create(opcPackage)) {
try (ByteArrayOutputStream bos = new ByteArrayOutputStream()) {
workbook.write(bos);
return bos.toByteArray();
}
}
}
}

Multipart File to File InputStream

How can I convert a MultipartFile to FileInputStream in memory?
I have tried to below , but i am facing the error as
org.springframework.web.multipart.commons.CommonsMultipartFile cannot
be cast to java.io.File
My Code is
FileInputStream fis = new FileInputStream((File)file);
where file is a multipart file
You can't create an instance of FileInputStream unless your file is not on file system.
You have to either first save the multipart file in temporary location on server using
file.transferTo(tempFile);
InputStream stream = new FileInputStream(tempFile);
But multipart file can also be read simply via basic streams methods such as
InputStream inputStream = new BufferedInputStream(file.getInputStream());
Try using:
MultipartFile uploadedFile = ((MultipartHttpServletRequest)request).getFile('file_name')
InputStream inputStream = new ByteArrayInputStream(uploadedFile?.getBytes())
Take look at MultipartFile
In that you can go with :
void transferTo(File dest)
This method transfer the received file to the given destination file.
MultipartFile file;
InputStream inputStream = file.getInputStream();
To convert Multipart file to Input Stream
MultipartFile file;
InputStream inputStream = new InputStream(file.getInputStream());
This worked for me.
We may just cast and use like below
FileInputStream file = (FileInputStream) multipartFile.getInputStream();
For a multipart file eg:
FileMultipartData part = new FileMultipartData();
InputStream inputStream = part.getFileMultipart().get(0).getByteStream();
This worked for me in my code. Please try it

how to Typecast File object into InputStream

How to Typecast File object into InputStream.
File file=new File("c:\\abc.txt");
Thanks
File file=new File("c:\\abc.txt");
InputStream is = new FileInputStream(file);
or
InputStream is = new FileInputStream("c:\\abc.txt");
You don't typecast the file to Input stream, you create an InputStream object using the file as parameter. You can use FileInputStream:
FileInputStream fis = new FileInputStream(file);
Use file as a parameter in a FileInputStream Object.
Like this,
FileInputStream fis = new FileInputStream(file);
Creates a FileInputStream by opening a connection to an actual file,
the file named by the File object file in the file system. A new
FileDescriptor object is created to represent this file connection.

Categories