In my application, I am getting excel file in chunks as input. Let say, if excel file size is 20 MB then I will get 4 chunks, where each chunk(byte[]) is of 5MB. I am writing each chunk (byte[]) into temp file (with no extension). I am using this temp file to regenerate actual excel file which is sent to me in multiple chunks. My requirement is that generated excel file must be same as the excel file which I got in chunks.
Sample Code:
Reading excel file, converting into chunks and writing those chunks to temp file.
public static void readExcelFileBytes(String srcFile) throws IOException {
File file = new File(srcFile); FileInputStream fis = new FileInputStream(file); byte[] buf = new byte[1024 * 5]; // 5KB int totalNoOfBytes = 0; try { for (int readNum; (readNum = fis.read(buf)) != -1;) { appendByteArrayToTempFile(buf); } } catch (IOException ex) { ex.printStackTrace(); } System.out.println("Read: Total Size Bytes" + totalNoOfBytes); } public static boolean appendByteArrayToTempFile(byte[] byteArray) { boolean result = false; BufferedWriter writeout = null; File bodfile = null; FileOutputStream out = null; try { bodfile = new File("C://tempFile"); out = new FileOutputStream(bodfile, true); out.write(byteArray); result = true; } catch (IOException ex) { ex.printStackTrace(); } finally { try { //writeout.close(); out.close(); } catch (IOException ex) { ex.printStackTrace(); } } return result; }
Using temp byte[] to regenerate excel file.
public static void tempToFile(String srcFilePath) throws IOException{
File file = new File("C://tempFile");
FileInputStream fis = new FileInputStream(file);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
byte[] buf = new byte[1024];
try {
for (int readNum; (readNum = fis.read(buf)) != -1;) {
bos.write(buf, 0, readNum); //no doubt here is 0
}
} catch (IOException ex) {
ex.printStackTrace();
}
byte[] bytes = bos.toByteArray();
// Create source file from Temp's byte array
FileOutputStream fileOuputStream = new FileOutputStream(srcFilePath);
fileOuputStream.write(bytes);
fileOuputStream.flush();
fileOuputStream.close();
}
Issue:
public static void main(String s[]) throws IOException {
// XLS POC
readExcelFileBytes("C://Input.xlsx");
tempToFile("C://Output.xlsx");
}
But when excel file is generated using temp file byte[], it gets currepted. Can somebody help me whether I am following proper way to re-generate excel file using temp file byte[]?