IOUtils.toString (InputStream)에 해당하는 Guava
Apache Commons IO 에는 문자열 을 읽을 수있는 편리한 메서드 IOUtils.toString () 이 InputStream
있습니다.
Apache Commons에서 Guava 로 이동하려고하므로 Guava 에 동등한 기능이 있습니까? com.google.common.io
패키지의 모든 클래스를 살펴 보았지만 거의 간단한 것을 찾을 수 없었습니다.
편집 : 나는 문자 세트와 관련된 문제를 이해하고 감사합니다. 내 모든 소스가 ASCII (예, ANSI가 아닌 ASCII 등)로되어 있다는 것을 알고 있으므로이 경우 인코딩은 나에게 문제가되지 않습니다.
Calum의 답변에 대한 귀하의 의견에서 사용할 예정이라고 말했습니다.
CharStreams.toString(new InputStreamReader(supplier.get(), Charsets.UTF_8))
이 코드는 과부하 CharStreams.toString(Readable)
상태로 인해 문제가 됩니다.
을 닫습니다하지 않습니다
Readable
.
즉 InputStreamReader
, 이 코드가 완료된 후에도 에서 InputStream
반환 된 supplier.get()
이 (가) 닫히지 않습니다.
반면에 이미있는 것으로 보이며 InputSupplier<InputStream>
오버로드를 사용 했다는 사실을 활용 CharStreams.toString(InputSupplier<R extends Readable & Closeable>
하면 toString
메서드가의 생성과 종료를 모두 처리 Reader
합니다.
이것은 정확히 Jon Skeet이 제안한 것입니다. 단, 실제로 입력으로받는 오버로드가 없다는 점을 제외 CharStreams.newReaderSupplier
하면 다음 InputStream
과 같이 제공해야합니다 InputSupplier
.
InputSupplier<? extends InputStream> supplier = ...
InputSupplier<InputStreamReader> readerSupplier =
CharStreams.newReaderSupplier(supplier, Charsets.UTF_8);
// InputStream and Reader are both created and closed in this single call
String text = CharStreams.toString(readerSupplier);
요점은 InputSupplier
Guava가 추악한 try-finally
블록 이 필요한 부품을 처리하여 리소스가 제대로 닫히 도록 허용함으로써 삶을 더 쉽게 만드는 것입니다.
편집 : 개인적으로 다음을 찾습니다 (실제로 작성하는 방법은 위 코드의 단계를 분해하는 것입니다)
String text = CharStreams.toString(
CharStreams.newReaderSupplier(supplier, Charsets.UTF_8));
일하기 훨씬 덜 장황 이보다 :
String text;
InputStreamReader reader = new InputStreamReader(supplier.get(),
Charsets.UTF_8);
boolean threw = true;
try {
text = CharStreams.toString(reader);
threw = false;
}
finally {
Closeables.close(reader, threw);
}
이 문제를 직접 처리하기 위해 작성해야 할 내용이 어느 정도 있습니다.
편집 : 2014 년 2 월
InputSupplier
그리고 OutputSupplier
이를 사용하는 방법은 Guava 16.0에서 더 이상 사용되지 않습니다. 이들의 교체는 ByteSource
, CharSource
, ByteSink
와 CharSink
. 가 주어지면 ByteSource
이제 다음 String
과 같은 내용을 얻을 수 있습니다 .
ByteSource source = ...
String text = source.asCharSource(Charsets.UTF_8).read();
당신이 가지고있는 경우에 Readable
당신은 사용할 수 있습니다 CharStreams.toString(Readable)
. 따라서 다음을 수행 할 수 있습니다.
String string = CharStreams.toString( new InputStreamReader( inputStream, "UTF-8" ) );
어쨌든 당신이해야 할 문자 세트를 지정하도록 강요합니다.
UPDATE: Looking back, I don't like my old solution. Besides it is 2013 now and there are better alternatives available now for Java7. So here is what I use now:
InputStream fis = ...;
String text;
try ( InputStreamReader reader = new InputStreamReader(fis, Charsets.UTF_8)){
text = CharStreams.toString(reader);
}
or if with InputSupplier
InputSupplier<InputStreamReader> spl = ...
try ( InputStreamReader reader = spl.getInput()){
text = CharStreams.toString(reader);
}
Nearly. You could use something like this:
InputSupplier<InputStreamReader> readerSupplier = CharStreams.newReaderSupplier
(streamSupplier, Charsets.UTF_8);
String text = CharStreams.toString(readerSupplier);
Personally I don't think that IOUtils.toString(InputStream)
is "nice" - because it always uses the default encoding of the platform, which is almost never what you want. There's an overload which takes the name of the encoding, but using names isn't a great idea IMO. That's why I like Charsets.*
.
EDIT: Not that the above needs an InputSupplier<InputStream>
as the streamSupplier
. If you've already got the stream you can implement that easily enough though:
InputSupplier<InputStream> supplier = new InputSupplier<InputStream>() {
@Override public InputStream getInput() {
return stream;
}
};
Another option is to read bytes from Stream and create a String from them:
new String(ByteStreams.toByteArray(inputStream))
new String(ByteStreams.toByteArray(inputStream), Charsets.UTF_8)
It's not 'pure' Guava, but it's a little bit shorter.
Based on the accepted answer, here is a utility method that mocks the behavior of IOUtils.toString()
(and an overloaded version with a charset, as well). This version should be safe, right?
public static String toString(final InputStream is) throws IOException{
return toString(is, Charsets.UTF_8);
}
public static String toString(final InputStream is, final Charset cs)
throws IOException{
Closeable closeMe = is;
try{
final InputStreamReader isr = new InputStreamReader(is, cs);
closeMe = isr;
return CharStreams.toString(isr);
} finally{
Closeables.closeQuietly(closeMe);
}
}
There is much shorter autoclosing solution in case when input stream comes from classpath resource:
URL resource = classLoader.getResource(path);
byte[] bytes = Resources.toByteArray(resource);
String text = Resources.toString(resource, StandardCharsets.UTF_8);
Uses Guava Resources, inspired by IOExplained.
EDIT (2015): Okio is the best abstraction and tools for I/O in Java/Android that I know of. I use it all the time.
FWIW here's what I use.
If I already have a stream in hand, then:
final InputStream stream; // this is received from somewhere
String s = CharStreams.toString(CharStreams.newReaderSupplier(new InputSupplier<InputStream>() {
public InputStream getInput() throws IOException {
return stream;
}
}, Charsets.UTF_8));
If I'm creating a stream:
String s = CharStreams.toString(CharStreams.newReaderSupplier(new InputSupplier<InputStream>() {
public InputStream getInput() throws IOException {
return <expression creating the stream>;
}
}, Charsets.UTF_8));
As a concrete example, I can read an Android text file asset like this:
final Context context = ...;
String s = CharStreams.toString(CharStreams.newReaderSupplier(new InputSupplier<InputStream>() {
public InputStream getInput() throws IOException {
return context.getAssets().open("my_asset.txt");
}
}, Charsets.UTF_8));
For a concrete example, here's how I can read an Android text file asset:
public static String getAssetContent(Context context, String file) {
InputStreamReader reader = null;
InputStream stream = null;
String output = "";
try {
stream = context.getAssets().open(file);
reader = new InputStreamReader(stream, Charsets.UTF_8);
output = CharStreams.toString(reader);
} catch (IOException e) {
e.printStackTrace();
} finally {
if (stream != null) {
try {
stream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return output;
}
참고URL : https://stackoverflow.com/questions/4185665/guava-equivalent-for-ioutils-tostringinputstream
'Programing' 카테고리의 다른 글
TD 내에서 위치 상대 / 절대 위치를 사용하십니까? (0) | 2020.08.12 |
---|---|
Android : 콘텐츠 URI에서 파일 URI를 가져 오나요? (0) | 2020.08.12 |
Windows 용 Docker 오류 : "BIOS에서 하드웨어 지원 가상화 및 데이터 실행 보호를 활성화해야합니다." (0) | 2020.08.11 |
문자열이 유효한 날짜인지 확인하는 방법 (0) | 2020.08.11 |
단일 node.js 프로젝트의 몽구스 및 다중 데이터베이스 (0) | 2020.08.11 |