Guava equivalent for IOUtils.toString(InputStream)

前端 未结 9 1108
深忆病人
深忆病人 2020-12-04 16:00

Apache Commons IO has a nice convenience method IOUtils.toString() to read an InputStream to a String.

Since I am trying to move away from Apache Common

9条回答
  •  萌比男神i
    2020-12-04 16:50

    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() {
        public InputStream getInput() throws IOException {
            return stream;
        }
    }, Charsets.UTF_8));
    

    If I'm creating a stream:

    String s = CharStreams.toString(CharStreams.newReaderSupplier(new InputSupplier() {
        public InputStream getInput() throws IOException {
            return ;
        }
    }, 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() {
        public InputStream getInput() throws IOException {
            return context.getAssets().open("my_asset.txt");
        }
    }, Charsets.UTF_8));
    

提交回复
热议问题