2017-05-02 1 views
0

DeflaterOutputStream에 대해 ObjectOutputStream을 사용하여 수축 된 데이터를 기본 스트림에 쓰려고합니다. 그러나 그들의 InputStream 대응 물을 사용하여 데이터를 읽으려고하면 예외가 발생합니다. 참고로 Deflate{Output,Input}StreamGZip{Output,Input}Stream으로 바꾸면 예상대로 작동합니다. 이 동작을 보여줍니다 예제 코드는 아래에서 볼 수 있습니다 :DeflaterInputStream의 ObjectInputStream이 StreamCorruptedException을 throw합니다.

ByteArrayOutputStream baos = new ByteArrayOutputStream(); 
try(ObjectOutputStream oos = new ObjectOutputStream(new DeflaterOutputStream(baos))) { 
    oos.writeObject("test"); 
} 

ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray()); 
try(ObjectInputStream oos = new ObjectInputStream(new DeflaterInputStream(bais))) { 
    System.out.println(oos.readObject()); 
} 

그것은 다음과 같은 예외가 발생합니다 :

Exception in thread "main" java.io.StreamCorruptedException: invalid stream header: 789CAB98 
    at java.io.ObjectInputStream.readStreamHeader(ObjectInputStream.java:857) 
    at java.io.ObjectInputStream.<init>(ObjectInputStream.java:349) 
    at Main.main(Main.java:23) 
exacly 이런 일이 발생하는 이유

사람이 알고 있나요?

답변

1

저는 이미 알아 냈습니다. 어리석은 실수입니다. 하지만 내 자신의 질문에 답해 미래 사람들이 다시 떨어지지 않도록하십시오 :

DeflaterOutputStream의 역 클래스는 DeflaterInputStream이 아니라 InflaterInputStream입니다. 코드는 아래처럼 보입니다.

ByteArrayOutputStream baos = new ByteArrayOutputStream(); 
try(ObjectOutputStream oos = new ObjectOutputStream(new DeflaterOutputStream(baos))) { 
    oos.writeObject("test"); 
} 

ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray()); 
try(ObjectInputStream oos = new ObjectInputStream(new InflaterInputStream(bais))) { 
    System.out.println(oos.readObject()); 
} 
관련 문제