Guava equivalent for IOUtils.toString(InputStream)

前端 未结 9 1101
深忆病人
深忆病人 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:57

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

提交回复
热议问题