如果您有java.io.InputStream对象,应该如何处理该对象并生成String?
假设我有一个包含文本数据的InputStream,我想将其转换为String,例如,我可以将其写入日志文件。
获取InputStream并将其转换为字符串的最简单方法是什么?
public String convertStreamToString(InputStream is) {
// ???
}
如果您有java.io.InputStream对象,应该如何处理该对象并生成String?
假设我有一个包含文本数据的InputStream,我想将其转换为String,例如,我可以将其写入日志文件。
获取InputStream并将其转换为字符串的最简单方法是什么?
public String convertStreamToString(InputStream is) {
// ???
}
当前回答
一个很好的方法是使用Apache Commons IOUItils将InputStream复制到StringWriter中。。。类似于
StringWriter writer = new StringWriter();
IOUtils.copy(inputStream, writer, encoding);
String theString = writer.toString();
甚至
// NB: does not close inputStream, you'll have to use try-with-resources for that
String theString = IOUtils.toString(inputStream, encoding);
或者,如果不想混合流和写入器,可以使用ByteArrayOutputStream。
其他回答
就reduce和concat而言,它可以在Java 8中表示为:
String fromFile = new BufferedReader(new
InputStreamReader(inputStream)).lines().reduce(String::concat).get();
InputStream inputStream = null;
BufferedReader bufferedReader = null;
try {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
String stringBuilder = new StringBuilder();
String content;
while((content = bufferedReader.readLine()) != null){
stringBuilder.append(content);
}
System.out.println("content of file::" + stringBuilder.toString());
}
catch (IOException e) {
e.printStackTrace();
}finally{
if(bufferedReader != null){
try{
bufferedReader.close();
}catch(IoException ex){
ex.printStackTrace();
}
当输入流来自类路径资源(这似乎是一项流行任务)时,Guava提供了更短的高效自动关闭解决方案:
byte[] bytes = Resources.toByteArray(classLoader.getResource(path));
or
String text = Resources.toString(classLoader.getResource(path), StandardCharsets.UTF_8);
还有ByteSource和CharSource的一般概念,它们温和地负责打开和关闭流。
因此,例如,不要显式打开一个小文件来读取其内容:
String content = Files.asCharSource(new File("robots.txt"), StandardCharsets.UTF_8).read();
byte[] data = Files.asByteSource(new File("favicon.ico")).read();
或者只是
String content = Files.toString(new File("robots.txt"), StandardCharsets.UTF_8);
byte[] data = Files.toByteArray(new File("favicon.ico"));
嗯,你可以自己编程。。。这并不复杂。。。
String Inputstream2String (InputStream is) throws IOException
{
final int PKG_SIZE = 1024;
byte[] data = new byte [PKG_SIZE];
StringBuilder buffer = new StringBuilder(PKG_SIZE * 10);
int size;
size = is.read(data, 0, data.length);
while (size > 0)
{
String str = new String(data, 0, size);
buffer.append(str);
size = is.read(data, 0, data.length);
}
return buffer.toString();
}
Use:
InputStream in = /* Your InputStream */;
StringBuilder sb = new StringBuilder();
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String read;
while ((read=br.readLine()) != null) {
//System.out.println(read);
sb.append(read);
}
br.close();
return sb.toString();