如果有一個java.io.InputStream物件,應該如何處理該物件并產生一個String?
假設我有一個InputStream包含文本資料的檔案,并且想將其轉換String為,例如,我可以將其寫入日志檔案,
InputStream將并將其轉換為的最簡單方法是String什么?
public String convertStreamToString(InputStream is) { // ??? }
做到這一點的一種好方法是使用Apache commons IOUtils將apache復制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如果您不想將Streams和Writers混合使用,則可以使用
本文首發于java黑洞網,博客園同步更新
做到這一點的一種好方法是使用Apache commons IOUtils將apache復制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如果您不想將Streams和Writers混合使用,則可以使用
本文首發于java黑洞網,博客園同步更新
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/275654.html
標籤:Java
