来自 InputStream 的 Java 字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3479112/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 02:00:42  来源:igfitidea点击:

Java String from InputStream

javastream

提问by Ian Vink

Possible Duplicates:
How do I convert an InputStream to a String in Java?
In Java how do a read an input stream in to a string?

可能的重复:
如何在 Java 中将 InputStream 转换为字符串?
在 Java 中如何将输入流读入字符串?

I have an InputSteamand need to simply get a single simple Stringwith the complete contents.

我有一个InputSteam并且需要简单地获得一个String包含完整内容的简单。

How is this done in Java?

这是如何在 Java 中完成的?

采纳答案by x4u

Here is a modification of Gopi's answer that doesn't have the line ending problem and is also more effective as it doesn't need temporary String objects for every line and avoids the redundant copying in BufferedReader and the extra work in readLine().

这是 Gopi 答案的修改,它没有行结束问题,而且更有效,因为它不需要每一行的临时 String 对象,并避免了 BufferedReader 中的冗余复制和 readLine() 中的额外工作。

public static String convertStreamToString( InputStream is, String ecoding ) throws IOException
{
    StringBuilder sb = new StringBuilder( Math.max( 16, is.available() ) );
    char[] tmp = new char[ 4096 ];

    try {
       InputStreamReader reader = new InputStreamReader( is, ecoding );
       for( int cnt; ( cnt = reader.read( tmp ) ) > 0; )
            sb.append( tmp, 0, cnt );
    } finally {
        is.close();
    }
    return sb.toString();
}

回答by Jon Skeet

You need to construct an InputStreamReaderto wrap the input stream, converting between binary data and text. Specify the appropriate encoding based on your input source.

您需要构造一个InputStreamReader来包装输入流,在二进制数据和文本之间进行转换。根据您的输入源指定适当的编码。

Once you've got an InputStreamReader, you could create a BufferedReaderand read the contents line by line, or just read buffer-by-buffer and append to a StringBuilderuntil the read()call returns -1.

一旦你有了InputStreamReader,你可以创建一个BufferedReader并逐行读取内容,或者只是逐个缓冲区读取并附加到 aStringBuilder直到read()调用返回-1。

The Guavalibrary makes the second part of this easy - use CharStreams.toString(inputStreamReader).

番石榴库使得这个简单的第二部分-使用CharStreams.toString(inputStreamReader)

回答by hhbarriuso

回答by Gopi

Here is an example code adapted from here.

这是改编自此处的示例代码。

public  String convertStreamToString(InputStream is) throws IOException {
        /*
         * To convert the InputStream to String we use the BufferedReader.readLine()
         * method. We iterate until the BufferedReader return null which means
         * there's no more data to read. Each line will appended to a StringBuilder
         * and returned as String.
         */
        if (is != null) {
            StringBuilder sb = new StringBuilder();
            String line;

            try {
               BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
                while ((line = reader.readLine()) != null) {
                    sb.append(line).append("\n");
                }
            } finally {
                is.close();
            }
            return sb.toString();
        } else {       
            return "";
        }
    }

回答by maerics

You could also use a StringWriteras follows; each readfrom your InputStream is matched with a write(or append) to the StringWriter, and upon completion you can call getBufferto get a StringBuffer which could be used directly or you could get call its toStringmethod.

您还可以按如下方式使用StringWriterreadInputStream 中的每个都与StringWriter的write(或append)匹配,完成后,您可以调用getBuffer以获取可以直接使用的 StringBuffer,也可以调用其toString方法。

回答by Thorbj?rn Ravn Andersen

Wrap the Stream in a Reader to get locale conversion, and then keep reading while collecting in a StringBuffer. When done, do a toString() on the StringBuffer.

将 Stream 包裹在 Reader 中以进行区域设置转换,然后在收集到 StringBuffer 的同时继续阅读。完成后,对 StringBuffer 执行 toString()。