Reader를 InputStream으로, Writer를 OutputStream으로 변환하는 방법은 무엇입니까?
텍스트 인코딩 문제를 피하는 쉬운 방법이 있습니까?
텍스트 인코딩 문제를 실제로 피할 수는 없지만 기존 솔루션이 있습니다.
Reader
받는 사람InputStream
:ReaderInputStream
Writer
받는 사람OutputStream
:WriterOutputStream
원하는 인코딩을 선택하기 만하면됩니다.
문자열로 시작하는 경우 다음을 수행 할 수도 있습니다.
new ByteArrayInputStream(inputString.getBytes("UTF-8"))
글쎄, 리더는 문자를 처리하고 InputStream은 바이트를 처리합니다. 인코딩은 문자를 바이트로 표현하는 방법을 지정하므로 문제를 무시할 수 없습니다. 문제를 피하는 것과 관련하여 제 의견은 하나의 문자 집합 (예 : "UTF-8")을 선택하고 그대로 유지하는 것입니다.
실제로 수행하는 방법과 관련하여 지적했듯이 " 이러한 클래스의 명백한 이름은 ReaderInputStream 및 WriterOutputStream 입니다. "놀랍게도 " 이들은 '반대'클래스 인 InputStreamReader 및 OutputStreamWriter 가 Java 라이브러리에 포함되어 있지 않습니다. 포함.
따라서 많은 사람들이 Apache Commons IO를 포함하여 자체 구현을 제안했습니다 . 라이선스 문제에 따라 프로젝트에 commons-io 라이브러리를 포함하거나 소스 코드의 일부를 복사 할 수도 있습니다 ( 여기에서 다운로드 가능 ).
- Apache ReaderInputStream : API / 소스 코드 직접 링크
- Apache WriterOutputStream : API / 소스 코드 직접 링크
보시다시피 두 클래스의 문서에는 "JRE에서 지원하는 모든 문자 집합 인코딩이 올바르게 처리됩니다"라고 나와 있습니다.
NB 여기에있는 다른 답변 중 하나에 대한 의견은 이 버그를 언급 합니다 . 그러나 이는 Apache Commons IO ReaderInputStream 클래스가 아닌 Apache Ant ReaderInputStream 클래스 ( 여기 )에 영향을줍니다 .
또한 문자열로 시작하는 경우 다음 과 같이 Commons IO 에서 org.apache.commons.io.IOUtils를 사용하여 StringReader 생성을 건너 뛰고 한 단계로 InputStream을 생성 할 수 있습니다 .
InputStream myInputStream = IOUtils.toInputStream(reportContents, "UTF-8");
물론 여전히 텍스트 인코딩에 대해 생각할 필요가 있지만 적어도 변환은 한 단계로 이루어집니다.
사용하다:
new CharSequenceInputStream(html, StandardCharsets.UTF_8);
이 방법에 대한 선행 변환이 필요하지 않습니다 String
다음에 byte[]
보고서가 큰 경우, 할당 더 많은 힙 메모리를. StringBuffer에서 바로 스트림을 읽을 때 즉석에서 바이트로 변환합니다.
Apache Commons IO 프로젝트의 CharSequenceInputStream 을 사용합니다 .
commons-io 2.0 에는WriterOutputStream
이러한 클래스의 분명한 이름은 ReaderInputStream 및 WriterOutputStream입니다. 불행히도 이들은 Java 라이브러리에 포함되어 있지 않습니다. 그러나 Google은 당신의 친구입니다.
악몽 같은 모든 텍스트 인코딩 문제를 해결할 수 있을지 모르겠습니다.
RFE가 있지만 Closed이며 수정되지 않습니다.
텍스트 인코딩 문제를 피할 수는 없지만 Apache commons-io 에는
이것들은 koders.com에 대한 Peter의 답변에서 언급 된 라이브러리이며 소스 코드 대신 라이브러리에 대한 링크입니다.
Are you trying to write the contents of a Reader
to an OutputStream
? If so, you'll have an easier time wrapping the OutputStream
in an OutputStreamWriter
and write the char
s from the Reader
to the Writer
, instead of trying to convert the reader to an InputStream
:
final Writer writer = new BufferedWriter(new OutputStreamWriter( urlConnection.getOutputStream(), "UTF-8" ) );
int charsRead;
char[] cbuf = new char[1024];
while ((charsRead = data.read(cbuf)) != -1) {
writer.write(cbuf, 0, charsRead);
}
writer.flush();
// don't forget to close the writer in a finally {} block
A warning when using WriterOutputStream - it doesn't always handle writing binary data to a file properly/the same as a regular output stream. I had an issue with this that took me awhile to track down.
If you can, I'd recommend using an output stream as your base, and if you need to write strings, use an OUtputStreamWriter wrapper around the stream to do it. It is far more reliable to convert text to bytes than the other way around, which is likely why WriterOutputStream is not a part of the standard Java library
Cactoos 를 사용할 수 있습니다 (정적 메서드 없음, 개체 만) :
다른 방법으로도 변환 할 수 있습니다.
Java가 제공하는 것만 사용하여 스트림에서 문자열을 읽는 경우.
InputStream s = new BufferedInputStream( new ReaderInputStream( new StringReader("a string")));
'program story' 카테고리의 다른 글
BigDecimal에서>, =, <와 같은 비교 연산자를 사용하는 방법 (0) | 2020.09.11 |
---|---|
Typescript 수면 (0) | 2020.09.11 |
패키지에있는 Python 모듈의 이름을 나열하는 표준 방법이 있습니까? (0) | 2020.09.11 |
C #에서 스트림을 사용하여 큰 텍스트 파일 읽기 (0) | 2020.09.11 |
안드로이드에서 확인 버튼을 클릭하면 URL 열기 (0) | 2020.09.11 |