如果您有java.io.InputStream对象,应该如何处理该对象并生成String?
假设我有一个包含文本数据的InputStream,我想将其转换为String,例如,我可以将其写入日志文件。
获取InputStream并将其转换为字符串的最简单方法是什么?
public String convertStreamToString(InputStream is) {
// ???
}
如果您有java.io.InputStream对象,应该如何处理该对象并生成String?
假设我有一个包含文本数据的InputStream,我想将其转换为String,例如,我可以将其写入日志文件。
获取InputStream并将其转换为字符串的最简单方法是什么?
public String convertStreamToString(InputStream is) {
// ???
}
当前回答
这里或多或少有sampath的答案,清理了一点并表示为函数:
String streamToString(InputStream in) throws IOException {
StringBuilder out = new StringBuilder();
BufferedReader br = new BufferedReader(new InputStreamReader(in));
for(String line = br.readLine(); line != null; line = br.readLine())
out.append(line);
br.close();
return out.toString();
}
其他回答
以下是我经过一些实验后提出的最优雅、纯Java(无库)解决方案:
public static String fromStream(InputStream in) throws IOException
{
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
StringBuilder out = new StringBuilder();
String newLine = System.getProperty("line.separator");
String line;
while ((line = reader.readLine()) != null) {
out.append(line);
out.append(newLine);
}
return out.toString();
}
这是我的基于Java 8的解决方案,它使用新的流API来收集InputStream中的所有行:
public static String toString(InputStream inputStream) {
BufferedReader reader = new BufferedReader(
new InputStreamReader(inputStream));
return reader.lines().collect(Collectors.joining(
System.getProperty("line.separator")));
}
我有log4j可用,所以我可以使用org.apache.log4j.lf5.util.StreamUtils.getBytes来获取字节,我可以使用Stringctor将其转换为字符串
String result = new String(StreamUtils.getBytes(inputStream));
此外,您还可以从指定的资源路径获取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;
}
String inputStreamToString(InputStream inputStream, Charset charset) throws IOException {
try (
final StringWriter writer = new StringWriter();
final InputStreamReader reader = new InputStreamReader(inputStream, charset)
) {
reader.transferTo(writer);
return writer.toString();
}
}
纯Java标准库解决方案-无库自Java 10以来-Reader#transferTo(Java.io.Writer)无环溶液无新行字符处理