我有以下问题。我写了Stream类,它扩展了OutputStream。这是代码:
import java.io.IOException;
import java.io.OutputStream;
public class ToUpperLetterOutputStream extends OutputStream {
public OutputStream outputStream;
public ToUpperLetterOutputStream(OutputStream outputStream)
{
this.outputStream = outputStream;
}
@Override
public void write(int b) {
char ch = toUpper((char)b);
try {
outputStream.write((int)ch);
} catch (IOException e) {
System.err.println("IO ERROR");
}
}
protected char toUpper(int b)
{
char ch = (char)b;
if (Character.isLowerCase(b))
{
ch = Character.toUpperCase(ch);
}
return ch;
}
}
现在我正在尝试将流与GZIPOutputStream一起使用:
byte[] bytes = stringBuilder.toString().getBytes();
try (
GZIPOutputStream g = new GZIPOutputStream( new ToUpperLetterOutputStream(
new FileOutputStream("result")))) {
g.write(bytes, 0, bytes.length);
g.finish();
} catch (FileNotFoundException e) {
System.err.println("Nie znaleziono pliku");
} catch (IOException e) {
System.err.println("IO Error");
}
程序运行正常,但是当我尝试解压缩结果文件时,出现以下异常:
java.util.zip.ZipException: invalid literal/lengths set
at java.util.zip.InflaterInputStream.read(InflaterInputStream.java:164)
at java.util.zip.GZIPInputStream.read(GZIPInputStream.java:117)
at java.io.FilterInputStream.read(FilterInputStream.java:107)
at Test.decompressGzipFile(Test.java:36)
at Test.main(Test.java:50)
当我不使用Stream时,解压缩效果很好。为什么会发生这种情况,我应该进行哪些更改以使此代码正确?