我正在尝试将长字符串压缩到文件中并检索它。
以下代码不起作用。它检索到的是胡言乱语。
public static void main(String args[]) {
try {
// Creating base for data
StringBuilder sbb = new StringBuilder();
for (int i=0;i<1000;i++)
sbb.append("ùertyty!|").append(Integer.toString(i));
File FileAll = new File(".\All.data");
FileAll.createNewFile();
// Zipping into file
DeflaterOutputStream g = new DeflaterOutputStream(
new FileOutputStream(FileAll));
OutputStreamWriter osw = new OutputStreamWriter(g);
String base = sbb.toString();
osw.write(base);
osw.close();
FileInputStream ALL_FIS = new FileInputStream(FileAll);
// Re-reading from file
DeflaterInputStream dis = new DeflaterInputStream(ALL_FIS);
InputStreamReader isr = new InputStreamReader(dis);
StringBuilder sb = new StringBuilder();
char[] c = new char[1000];
int count = isr.read(c);
while ( count != -1 ) {
sb.append(c, 0, count);
count = isr.read(c);
}
isr.close();
String retr = sb.toString();
System.out.println("Are equal: " + retr.equals(base));
System.out.println("Base: " + base);
System.out.println("Retr: " + retr);
} catch (IOException e) {
System.err.println(e.toString());
}
}
我做错了什么?
PS:似乎DeflaterInputStream没有完成它的工作,并按原样返回文件的内容。
您需要使用 InflaterInputStream(解压缩)而不是 DeflaterInputStream
http://download.oracle.com/javase/1.5.0/docs/api/java/util/zip/InflaterInputStream.html