[2
本文探討了Java中的文件壓縮和解壓縮,重點介紹了 fordaterinputStream
[2
Java提供了內置支持,用於使用
package來壓縮和解壓縮文件。 deflateroutputstream
將數據壓縮到縮放格式中(通常在zip檔案中使用),而
示例:將文件壓縮到zip
此示例演示瞭如何將文件壓縮到zip檔案中:
嘗試 {
文件文件=新文件(filepath);
字符串zipfileName = file.getName()“ .zip”;
fileOutputStream fos = new fileOutputStream(zipfileName);
zipoutputStream zos = new zipoutputstream(fos);
zos.putnextentry(new zipentry(file.getName()));
字節[] bytes = files.readallBytes(paths.get(filepath));
zos.write(bytes,0,bytes.length);
zos.closeentry();
Zos.Close();
} catch(filenotfoundException ex){
system.err.format(“找不到文件:%s%n”,filepath);
} catch(ioexception ex){
system.err.println(“ i/o錯誤:” ex);
}
算法用於文件compression/decompression:
[2 創建
fileOutputputStreamdeflateroutputputstream
以寫下壓縮數據。使用try {
File file = new File(filePath);
String zipFileName = file.getName() ".zip";
FileOutputStream fos = new FileOutputStream(zipFileName);
ZipOutputStream zos = new ZipOutputStream(fos);
zos.putNextEntry(new ZipEntry(file.getName()));
byte[] bytes = Files.readAllBytes(Paths.get(filePath));
zos.write(bytes, 0, bytes.length);
zos.closeEntry();
zos.close();
} catch (FileNotFoundException ex) {
System.err.format("File not found: %s%n", filePath);
} catch (IOException ex) {
System.err.println("I/O error: " ex);
}
,以及關閉的流。
decompression: fileInputStream anflaterInputStream
以讀取和解壓縮數據。 使用和關閉流。
錯誤處理:
fileInputStream inputStream = new fileInputStream(inputPath);
FileOutputStream outputStream = new FileOutputStream(outputpath);
DeflaterOutputStream Compressor = new DeflaterOutputStream(outputStream);
// ...從Inputstream到壓縮機寫數據...
compressor.close();
減壓:
zipoutputstream
的單文件壓縮,以及一個更複雜的示例。 處理目錄需要遞歸處理以遍歷目錄結構。 請注意,原始代碼示例缺乏正確的文件路徑處理和錯誤管理,從而導致 filenotfoundexception
。 始終確保可靠的錯誤處理並在代碼中指定正確的文件路徑。
AfferaterInputStream
以及正確的錯誤處理和文件路徑管理對於創建可靠和有效的壓縮實用程序至關重要。 請記住要始終處理潛在的異常,並向用戶提供適當的錯誤消息。
免責聲明: 提供的所有資源部分來自互聯網,如果有侵犯您的版權或其他權益,請說明詳細緣由並提供版權或權益證明然後發到郵箱:[email protected] 我們會在第一時間內為您處理。
Copyright© 2022 湘ICP备2022001581号-3