在java中,如何将压缩文件中的内容读取和向压缩文件中写入内容呢,下面是相关代码:
先看如何从文本文件中读入代码
class="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
}