如何将长字符串压缩到文件中并检索它?
我正在尝试将一个长字符串压缩到一个文件中并检索它。
下面的代码不起作用。它检索到的是乱码。
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 没有完成其工作并按原样返回文件的内容。
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);
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());
}
}
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您需要使用 InflaterInputStream (解压缩)而不是 DeflaterInputStream
http://download.oracle.com/javase/1.5.0/docs/api/java/util/zip/InflaterInputStream.html
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