如果您有java.io.InputStream对象,应该如何处理该对象并生成String?


假设我有一个包含文本数据的InputStream,我想将其转换为String,例如,我可以将其写入日志文件。

获取InputStream并将其转换为字符串的最简单方法是什么?

public String convertStreamToString(InputStream is) {
// ???
}

当前回答

将inputStream转换为字符串的方法

public static String getStringFromInputStream(InputStream inputStream) {

    BufferedReader bufferedReader = null;
    StringBuilder stringBuilder = new StringBuilder();
    String line;

    try {
        bufferedReader = new BufferedReader(new InputStreamReader(
                inputStream));
        while ((line = bufferedReader.readLine()) != null) {
            stringBuilder.append(line);
        }
    } catch (IOException e) {
        logger.error(e.getMessage());
    } finally {
        if (bufferedReader != null) {
            try {
                bufferedReader.close();
            } catch (IOException e) {
                logger.error(e.getMessage());
            }
        }
    }
    return stringBuilder.toString();
}

其他回答

此外,您还可以从指定的资源路径获取InputStream:

public static InputStream getResourceAsStream(String path)
{
    InputStream myiInputStream = ClassName.class.getResourceAsStream(path);
    if (null == myiInputStream)
    {
        mylogger.info("Can't find path = ", path);
    }

    return myiInputStream;
}

要从特定路径获取InputStream,请执行以下操作:

public static URL getResource(String path)
{
    URL myURL = ClassName.class.getResource(path);
    if (null == myURL)
    {
        mylogger.info("Can't find resource path = ", path);
    }
    return myURL;
}

使用java 9中支持的java.io.InputStream.transferTo(OutputStream)和ByteArrayOutputStream.toString(String),该字符串采用字符集名称:

public static String gobble(InputStream in, String charsetName) throws IOException {
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    in.transferTo(bos);
    return bos.toString(charsetName);
}

JDK中最简单的方法是使用以下代码片段。

String convertToString(InputStream in){
    String resource = new Scanner(in).useDelimiter("\\Z").next();
    return resource;
}

如果您使用的是AWS SDK v2,请调用IoUtils.toUtf8String():

public String convertStreamToString(InputStream is) {
    return IoUtils.toUtf8String(is);
}

最简单的方法,一行:

public static void main(String... args) throws IOException {
    System.out.println(new String(Files.readAllBytes(Paths.get("csv.txt"))));
}