向压缩文件中写入和读出文件内容示例

在java中,如何将压缩文件中的内容读取和向压缩文件中写入内容呢,下面是相关代码:

先看如何从文本文件中读入代码


private String readFile(String fileName) {
StringBuilder sb = new StringBuilder();
try {
BufferedReader input = new BufferedReader(new FileReader(new File(fileName)));
try
{
String line=null;
while ((line==input.readLine()!=null)
{
sb.append(line);

}
} finally {
input.close();
}
} catch (IOException ex) {
// Handle exception
return null;
}

return sb.toString();





从gzip中读取内容:


private String readCompressedFile(String fileName) {
try {
GZIPInputStream gis = new GZIPInputStream(new FileInputStream(fileName));
ByteArrayOutputStream fos = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len;
while ((len = gis.read(buffer)) != -1) {
fos.write(buffer, 0, len);
}
fos.close();
gis.close();
return new String(fos.toByteArray());
} catch (IOException ex) {
// Handle exception
return null;
}
}



向gzip中写内容:


private void writeCompressedFile(String fileName, String value) {
try {
InputStream is = new ByteArrayInputStream(value.getBytes());
GZIPOutputStream gzipOS = new GZIPOutputStream(new FileOutputStream(fileName));
byte[] buffer = new byte[1024];
int len;
while ((len = is.read(buffer)) != -1) {

gzipOS.write(buffer,0,len);

}
gzipOS.close();
is.close();
} catch (IOException ex) {
// Handle exception
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值