Guava equivalent for IOUtils.toString(InputStream)

前端 未结 9 1093
深忆病人
深忆病人 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条回答
  •  一生所求
    2020-12-04 16:42

    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);
        }
    }
    

提交回复
热议问题