我有要求將上傳的電子表格存儲到磁盤。我正在使用下面的代碼來執行相同的操作,並且接收文件是從Excel中損壞的錯誤。使用java將電子表格保存到磁盤
byte[] bytes = null;
File uploadedFile = new File("D://xlsxTest//BNG Issue.xlsx");
File file = new File("D://xlsxTest//sample1.xlsx");
FileOutputStream outStream = null;
InputStream inputStream = null;
try{
if(!file.exists()){
file.createNewFile();
}
outStream = new FileOutputStream(file);
if (uploadedFile != null) {
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
inputStream = new FileInputStream(uploadedFile);;
int c = 0;
while (c != -1) {
c = inputStream.read();
byteArrayOutputStream.write((char) c);
}
bytes = byteArrayOutputStream.toByteArray();
}
outStream.write(bytes);
}catch(Exception e){
e.printStackTrace();
}finally{
try{
outStream.close();
}catch(Exception e){
e.printStackTrace();
}
}
我試過使用一個83KB大小的文件,結果文件是82.5KB。 任何幫助,將不勝感激。 謝謝。
看起來像你保存正確,不能讀取裏面的文本? –
嘗試在關閉它之前添加'outStream.flush()'。 – Berger
無法重現。您的代碼只是在文件末尾添加一個額外的字節(-1),因爲在寫入之後,文件結尾的測試發生**。但它不應該導致較短的副本。您是否可以確認使用上面的代碼「D://xlsxTest//sample1.xlsx」短於「D:// xlsxTest // BNG Issue.xlsx」? –