我是java的新手,刚开始昨天。由于我是一个学习做事的忠实粉丝,我正在用它做一个小项目。但我被困在这一部分。我用这个函数编写了一个文件:
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
null字符。以下是我尝试读取压缩文件的方法:
try (InputStream is = new InflaterInputStream(new FileInputStream(destFile))) {
}
我完全被困在这里。问题是,如何丢弃前几个字符直到'\ 0',然后将其余的解压缩文件写入控制台。
答案 0 :(得分:0)
while (is.read() != '\0');
答案 1 :(得分: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 }