Skip to content

Latest commit

 

History

History
62 lines (49 loc) · 2.18 KB

File metadata and controls

62 lines (49 loc) · 2.18 KB

如何在 Java 中将InputStream转换为字符串

原文: https://beginnersbook.com/2013/12/how-to-convert-inputstream-to-string-in-java/

以下是如何读取InputStream并将其转换为String的完整示例。涉及的步骤是:

1)我使用getBytes()方法 将文件内容转换为字节之后,使用包含内部缓冲区的ByteArrayInputStream初始化InputStream,缓冲区包含可以从流中读取的字节。

2)使用InputStreamReader读取InputStream

3)使用BufferedReader读取InputStreamReader

4)将BufferedReader读取的每一行附加到StringBuilder对象上。

5)最后使用toString()方法将StringBuilder转换为String

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

public class Example {
   public static void main(String[] args) throws IOException {
       InputStreamReader isr = null;
       BufferedReader br = null;
       InputStream is = 
            new ByteArrayInputStream("This is the content of my file".getBytes());
       StringBuilder sb = new StringBuilder();
       String content;
       try {
           isr = new InputStreamReader(is);
	   br = new BufferedReader(isr);
	   while ((content = br.readLine()) != null) {
		sb.append(content);
	   }
	} catch (IOException ioe) {
		System.out.println("IO Exception occurred");
		ioe.printStackTrace();	
	   } finally {
		isr.close();
		br.close();
	      }
        String mystring = sb.toString();
	System.out.println(mystring);
   }
}

输出:

This is the content of my file

参考: