可能重复:
In Java how do a read/convert an InputStream in to a string?BufferedInputStream字符串转换?
您好我想把这变成BufferedInputStream为我的字符串我怎样才能做到这一点?
BufferedInputStream in = new BufferedInputStream(sktClient.getInputStream());
String a= in.read();
可能重复:
In Java how do a read/convert an InputStream in to a string?BufferedInputStream字符串转换?
您好我想把这变成BufferedInputStream为我的字符串我怎样才能做到这一点?
BufferedInputStream in = new BufferedInputStream(sktClient.getInputStream());
String a= in.read();
BufferedInputStream in = new BufferedInputStream(sktClient.getInputStream());
byte[] contents = new byte[1024];
int bytesRead = 0;
String strFileContents;
while((bytesRead = in.read(contents)) != -1) {
strFileContents += new String(contents, 0, bytesRead);
}
System.out.print(strFileContents);
快速的谷歌搜索“java bufferedinputstream string”引发了大量的例子。 This人应该做的伎俩。
请下面的代码
让我知道结果
public String convertStreamToString(InputStream is)
throws IOException {
/*
* To convert the InputStream to String we use the
* Reader.read(char[] buffer) method. We iterate until the
35. * Reader return -1 which means there's no more data to
36. * read. We use the StringWriter class to produce the string.
37. */
if (is != null) {
Writer writer = new StringWriter();
char[] buffer = new char[1024];
try
{
Reader reader = new BufferedReader(
new InputStreamReader(is, "UTF-8"));
int n;
while ((n = reader.read(buffer)) != -1)
{
writer.write(buffer, 0, n);
}
}
finally
{
is.close();
}
return writer.toString();
} else {
return "";
}
}
感谢, Kariyachan
不需要铸造。 BufferedInputStream是一个InputStream – 2011-04-19 09:06:00
谢谢。更新 – DroidBot 2011-04-19 09:27:12
“谢谢,Kariyachan”我记得那个猫来自“来自U.N.C.L.E.的人” - 他现在是程序员? – 2014-04-02 17:42:10
随着Guava:
new String(ByteStreams.toByteArray(inputStream),Charsets.UTF_8);
随着Commons/IO:
IOUtils.toString(inputStream, "UTF-8")
我建议你使用Apache的百科全书IOUtils
String text = IOUtils.toString(sktClient.getInputStream());
如果你不想自己写的这一切(你应该不是真的) - 使用库为你做到这一点。
Apache commons-io就是这样做的。
如果您想要更精细的控制,请使用IOUtils.toString(InputStream)或IOUtils.readLines(InputStream)。
一个小错误。在while循环中,每次迭代都应该附加一个循环。它应该是+ =而不是=。即:strFileContents + =新字符串(内容,0,bytesRead); – 2014-06-26 20:54:46
@ JJ_Coder4Hire这不是唯一的错误,这段代码依赖于字符串编码在bytesRead标记处有一个边界的机会(对于ASCII,这是一个好的假设** ONLY **)。 – chacham15 2014-07-15 07:56:09
我不得不把'System.out.print(strFileContents);'内部循环,否则只显示我的html响应的最后一部分。 btw谢谢 – SaganTheBest 2015-01-14 14:54:44