programing tip

OutputStream을 문자열로 가져 오기

itbloger 2020. 10. 4. 10:39
반응형

OutputStream을 문자열로 가져 오기


java.io.OutputStream의 출력을 Java의 문자열로 파이프하는 가장 좋은 방법은 무엇입니까?

방법이 있다고 가정하십시오.

  writeToStream(Object o, OutputStream out)

객체의 특정 데이터를 주어진 스트림에 씁니다. 그러나이 출력을 가능한 한 쉽게 문자열로 가져오고 싶습니다.

나는 다음과 같은 수업을 작성하는 것을 고려하고 있습니다.

class StringOutputStream extends OutputStream {

  StringBuilder mBuf;

  public void write(int byte) throws IOException {
    mBuf.append((char) byte);
  }

  public String getString() {
    return mBuf.toString();
  }
}

그러나 더 나은 방법이 있습니까? 테스트 만하고 싶어요!


나는 ByteArrayOutputStream. 마지막으로 전화 할 수 있습니다.

new String( baos.toByteArray(), codepage );

이상 :

baos.toString( codepage );

를 들어 String생성자는이 codepage수 있습니다 String또는 인스턴스 java.nio.charset.Charset을 . 가능한 값은 java.nio.charset.StandardCharsets.UTF_8 입니다.

이 메소드 toString()매개 변수 String로 a 만 허용합니다 codepage(Java 8을 의미).


저는 Apache Commons IO 라이브러리를 좋아합니다. .NET FrameworktoString(String enc)메서드 가있는 ByteArrayOutputStream 버전을 살펴보십시오 toByteArray(). Commons 프로젝트와 같은 기존의 신뢰할 수있는 구성 요소를 사용하면 코드를 더 작고 쉽게 확장하고 용도를 ​​변경할 수 있습니다.


이것은 잘 작동했습니다.

    OutputStream output = new OutputStream()
    {
        private StringBuilder string = new StringBuilder();
        @Override
        public void write(int b) throws IOException {
            this.string.append((char) b );
        }

        //Netbeans IDE automatically overrides this toString()
        public String toString(){
            return this.string.toString();
        }
    };

메소드 호출 = >> marshaller.marshal( (Object) toWrite , (OutputStream) output);

그런 다음 문자열을 인쇄하거나 "출력"스트림 자체를 참조합니다. 예를 들어 문자열을 콘솔에 인쇄하려면 = >> System.out.println(output);

참고 : 내 메서드 호출 marshaller.marshal(Object,Outputstream)은 XML 작업을위한 것입니다. 이 주제와는 무관합니다.

This is highly wasteful for productional use, there is a way too many conversion and it is a bit loose. This was just coded to prove to you that it is totally possible to create a custom OuputStream and output a string. But just go Horcrux7 way and all is good with merely two method calls.

And the world lives on another day....


Here's what I ended up doing:

Obj.writeToStream(toWrite, os);
try {
    String out = new String(os.toByteArray(), "UTF-8");
    assertTrue(out.contains("testString"));
} catch (UnsupportedEncondingException e) {
    fail("Caught exception: " + e.getMessage());
}

Where os is a ByteArrayOutputStream.

참고URL : https://stackoverflow.com/questions/216894/get-an-outputstream-into-a-string

반응형