Java 读取InflateInputStream并解析结果
我对java很陌生,昨天才开始学习。因为我非常喜欢边做边学,所以我正在用它做一个小项目。但是我在这一部分中被绊倒了。我已使用此函数编写了一个文件:Java 读取InflateInputStream并解析结果,java,Java,我对java很陌生,昨天才开始学习。因为我非常喜欢边做边学,所以我正在用它做一个小项目。但是我在这一部分中被绊倒了。我已使用此函数编写了一个文件: public static boolean writeZippedFile(File destFile, byte[] input) { try { // create file if doesn't exist part was here try (OutputStream out = new Deflate
public static boolean writeZippedFile(File destFile, byte[] input) {
try {
// create file if doesn't exist part was here
try (OutputStream out = new DeflaterOutputStream(new FileOutputStream(destFile))) {
out.write(input);
}
return true;
} catch (IOException e) {
// error handlind was here
}
}
现在,我已经使用上述方法成功地编写了一个压缩文件,我想把它读回控制台。首先,我需要能够读取解压缩的内容,并将该内容的字符串表示形式写入控制台。但是,我还有第二个问题,我不想将字符最多写入第一个\0
空字符。以下是我尝试读取压缩文件的方式:
try (InputStream is = new InflaterInputStream(new FileInputStream(destFile))) {
}
我完全被困在这里了。问题是,如何在“\0”之前丢弃前几个字符,然后将解压缩文件的其余部分写入控制台。使用
我知道您的数据包含文本,因为您希望打印字符串表示。我进一步假设文本包含unicode字符。如果这是真的,那么您的控制台也应该支持unicode以正确显示字符 因此,您应该首先逐字节读取数据,直到遇到
\0
字符,然后您可以使用BufferedReader
将其余数据打印为文本行
try (InputStream is = new InflaterInputStream(new FileInputStream(destFile))) {
// read the stream a single byte each time until we encounter '\0'
int aByte = 0;
while ((aByte = is.read()) != -1) {
if (aByte == '\0') {
break;
}
}
// from now on we want to print the data
BufferedReader b = new BufferedReader(new InputStreamReader(is, "UTF8"));
String line = null;
while ((line = b.readLine()) != null) {
System.out.println(line);
}
b.close();
} catch(IOException e) { // handle }
不清楚你想做什么。解压后的数据在
字节[]输入中
对吗?您希望如何将它们写入控制台?作为字节?角色?他们的字符串表示法?@c.s.我发布的第一个代码只是为了向您展示我如何保存我现在想要读取的文件。解压后的数据不是字节[]输入
。我并没有任何解压版本的数据,我仍在研究如何读取解压后的数据。我发布的第二个代码是演示我试图读取压缩文件的努力。我想将它们作为字符串表示形式写入控制台。
try (InputStream is = new InflaterInputStream(new FileInputStream(destFile))) {
// read the stream a single byte each time until we encounter '\0'
int aByte = 0;
while ((aByte = is.read()) != -1) {
if (aByte == '\0') {
break;
}
}
// from now on we want to print the data
BufferedReader b = new BufferedReader(new InputStreamReader(is, "UTF8"));
String line = null;
while ((line = b.readLine()) != null) {
System.out.println(line);
}
b.close();
} catch(IOException e) { // handle }