前言日常工作中,經(jīng)常遇到將數(shù)據(jù)導(dǎo)出xml文件,為了方便需要進(jìn)行壓縮。代碼執(zhí)行中,如果文件流不及時關(guān)閉,導(dǎo)致xml文件內(nèi)容不完整。尤其是xml文件內(nèi)容比較大時,不容易發(fā)現(xiàn)問題,那么改如何解決呢? 代碼示例FileWriter fileWriter = new FileWriter(sourceFile); // 將XML文檔寫入文件 writer = new XMLWriter(fileWriter, OutputFormat.createPrettyPrint()); writer.write(document); //及時關(guān)閉 if (writer != null) { writer.close(); } fis = new FileInputStream(sourceFile); FileOutputStream fileOutput = new FileOutputStream(zipFile); ZipOutputStream zipOutput = new ZipOutputStream(fileOutput); ZipEntry zipEntry = new ZipEntry(id+".xml"); zipOutput.putNextEntry(zipEntry); byte[] buffer = new byte[1924]; int length; while((length=fis.read(buffer))>0){ zipOutput.write(buffer,0, length); } fis.close(); zipOutput.closeEntry(); zipOutput.close(); 解釋 writer.close();方法在壓縮前執(zhí)行,如果放代碼末尾,會導(dǎo)致壓縮后xml文件不完整,造成解析失敗。 |
|