How to zip long string into file and retrieve it?
I am trying to zip a long string into a file and to retrieve it.
The following code does not work. What it retrieves is gibberish.
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);
Input开发者_运维知识库StreamReader 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());
}
}
What am I doing wrong?
P.S.: It seems like DeflaterInputStream does not do its job and returns the content of the file as is.
You need to use a InflaterInputStream (which decompresses) instead of a DeflaterInputStream
http://download.oracle.com/javase/1.5.0/docs/api/java/util/zip/InflaterInputStream.html
精彩评论