如果您有java.io.InputStream对象,应该如何处理该对象并生成String?
假设我有一个包含文本数据的InputStream,我想将其转换为String,例如,我可以将其写入日志文件。
获取InputStream并将其转换为字符串的最简单方法是什么?
public String convertStreamToString(InputStream is) {
// ???
}
如果您有java.io.InputStream对象,应该如何处理该对象并生成String?
假设我有一个包含文本数据的InputStream,我想将其转换为String,例如,我可以将其写入日志文件。
获取InputStream并将其转换为字符串的最简单方法是什么?
public String convertStreamToString(InputStream is) {
// ???
}
当前回答
这个问题的解决方案不是最简单的,但由于没有提到NIO流和通道,这里有一个使用NIO通道和ByteBuffer将流转换为字符串的版本。
public static String streamToStringChannel(InputStream in, String encoding, int bufSize) throws IOException {
ReadableByteChannel channel = Channels.newChannel(in);
ByteBuffer byteBuffer = ByteBuffer.allocate(bufSize);
ByteArrayOutputStream bout = new ByteArrayOutputStream();
WritableByteChannel outChannel = Channels.newChannel(bout);
while (channel.read(byteBuffer) > 0 || byteBuffer.position() > 0) {
byteBuffer.flip(); //make buffer ready for write
outChannel.write(byteBuffer);
byteBuffer.compact(); //make buffer ready for reading
}
channel.close();
outChannel.close();
return bout.toString(encoding);
}
下面是如何使用它的示例:
try (InputStream in = new FileInputStream("/tmp/large_file.xml")) {
String x = streamToStringChannel(in, "UTF-8", 1);
System.out.println(x);
}
对于大型文件,此方法的性能应该很好。
其他回答
Apache Commons允许:
String myString = IOUtils.toString(myInputStream, "UTF-8");
当然,您可以选择UTF-8以外的其他字符编码。
另请参阅:(文档)
我已经创建了这段代码,并且它有效。没有所需的外部插件。
有一个字符串到流和流到字符串的转换器:
import java.io.ByteArrayInputStream;
import java.io.InputStream;
public class STRINGTOSTREAM {
public static void main(String[] args)
{
String text = "Hello Bhola..!\nMy Name Is Kishan ";
InputStream strm = new ByteArrayInputStream(text.getBytes()); // Convert String to Stream
String data = streamTostring(strm);
System.out.println(data);
}
static String streamTostring(InputStream stream)
{
String data = "";
try
{
StringBuilder stringbuld = new StringBuilder();
int i;
while ((i=stream.read())!=-1)
{
stringbuld.append((char)i);
}
data = stringbuld.toString();
}
catch(Exception e)
{
data = "No data Streamed.";
}
return data;
}
下面的代码对我有用。
URL url = MyClass.class.getResource("/" + configFileName);
BufferedInputStream bi = (BufferedInputStream) url.getContent();
byte[] buffer = new byte[bi.available() ];
int bytesRead = bi.read(buffer);
String out = new String(buffer);
请注意,根据Java文档,available()方法可能不适用于InputStream,但始终适用于BufferedInputStream。如果您不想使用available()方法,我们可以始终使用以下代码
URL url = MyClass.class.getResource("/" + configFileName);
BufferedInputStream bi = (BufferedInputStream) url.getContent();
File f = new File(url.getPath());
byte[] buffer = new byte[ (int) f.length()];
int bytesRead = bi.read(buffer);
String out = new String(buffer);
我不确定是否会有任何编码问题。如果代码有任何问题,请发表评论。
当输入流来自类路径资源(这似乎是一项流行任务)时,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"));
InputStream IS=new URL("http://www.petrol.si/api/gas_prices.json").openStream();
ByteArrayOutputStream BAOS=new ByteArrayOutputStream();
IOUtils.copy(IS, BAOS);
String d= new String(BAOS.toByteArray(),"UTF-8");
System.out.println(d);