Java 里把 InputStream 转换成 String 的几种方法

我们在 Java 中经常会碰到如何把 InputStream 转换成 String 的情形,比如从文件或网络得到一个 InputStream,需要转换成字符串输出或赋给别的变量。


未真正关注这个问题之前我常用的办法就是按字节一次次读到缓冲区,或是建立 BufferedReader 逐行读取。其实大可不必费此周折,我们可以用 Apache commons IOUtils,或者是 JDK 1.5 后的 Scanner,还可用 Google  Guava 库的 CharStreams。到了 JDK7,若要从文件中直接得到字符串还能用 java.nio.file.Files#readAllLines 和 java.nio.file.Files#readAllBytes 方法。

下面看各个例子,为能够实际用运,例子写在 main 方法里,并从文件获得一个 InputStream,代码中把可能要捕获的异常抛出来。再就是注意处理输入输出流时有涉及到字符集,字符集乱了就乱码了,默认字符集是 System.getProperty("file.encoding"),通常我们都用 UTF-8,异常 UnsupportedEncodingException 继承自 IOException。

下面的 6 个方法中应该有一个你能看得上的吧,用 Groovy,Scala 的除外,若未找到一个遂意的,告诉我,你有好办法更应该告诉我。

1. 使用 JDK 5 的 Scanner
 1package cc.unmi.test;
 2
 3import java.io.FileInputStream;
 4import java.io.FileNotFoundException;
 5import java.io.InputStream;
 6import java.util.Scanner;
 7
 8/**
 9 * 
10 * @author Unmi
11 * @Creation date: 2013-02-01
12 */
13public class Test {
14
15    /**
16     * @param args
17     * @throws FileNotFoundException 
18     */
19    public static void main(String[] args) throws FileNotFoundException {
20        InputStream inputStream = new FileInputStream("d:/sample.txt");
21        Scanner scanner = new Scanner(inputStream, "UTF-8");
22        String text = scanner.useDelimiter("\\A").next();
23        System.out.println(text);
24        scanner.close();
25    }
26}

2. JDK1.4 及之前的 BufferedReader 法
 1package cc.unmi.test;
 2
 3import java.io.BufferedReader;
 4import java.io.FileInputStream;
 5import java.io.IOException;
 6import java.io.InputStream;
 7import java.io.InputStreamReader;
 8
 9/**
10 * 
11 * @author Unmi
12 * @Creation date: 2013-02-01
13 */
14public class Test {
15
16    /**
17     * @param args
18     * @throws IOException 
19     */
20    public static void main(String[] args) throws IOException {
21        InputStream inputStream = new FileInputStream("d:/sample.txt");
22        StringBuilder stringBuilder = new StringBuilder();
23        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
24        boolean firstLine = true;
25        String line = null; ;
26        while((line = bufferedReader.readLine()) != null){
27            if(!firstLine){
28                stringBuilder.append(System.getProperty("line.separator"));
29            }else{
30                firstLine = false;
31            }
32            stringBuilder.append(line);
33        }
34        System.out.println(stringBuilder.toString());
35    }
36}

中间那些判断是不是第一行来决定是否加换行符是些杂音。

3. JDK1.4 及之前的 readBytes 法
 1package cc.unmi.test;
 2
 3import java.io.FileInputStream;
 4import java.io.IOException;
 5import java.io.InputStream;
 6
 7/**
 8 * 
 9 * @author Unmi
10 * @Creation date: 2013-02-01
11 */
12public class Test {
13
14    /**
15     * @throws IOException 
16     */
17    public static void main(String[] args) throws IOException {
18        InputStream inputStream = new FileInputStream("d:/sample.txt");
19        
20        byte[] buffer = new byte[2048];
21        int readBytes = 0;
22        StringBuilder stringBuilder = new StringBuilder();
23        while((readBytes = inputStream.read(buffer)) > 0){
24            stringBuilder.append(new String(buffer, 0, readBytes));
25        }
26        
27        System.out.println(stringBuilder.toString());
28    }
29}

缓冲区的大小自己根据实际来调,比 BufferedReader 还简洁些,不需管换行符的事情。

4. Apache commons IOUtils.toString 法
 1package cc.unmi.test;
 2
 3import java.io.*;
 4
 5import org.apache.commons.io.IOUtils;
 6
 7/**
 8 * 
 9 * @author Unmi
10 * @Creation date: 2013-02-01
11 */
12public class Test {
13
14    /**
15     * @throws IOException 
16     */
17    public static void main(String[] args) throws IOException {
18        InputStream inputStream = new FileInputStream("d:/sample.txt");
19        String text = IOUtils.toString(inputStream);
20        System.out.println(text);
21    }
22}

第三方库就是第三方库,人家充分考虑到了你的感受,你对 JDK 库的抱怨,多简洁,一行搞定。IOUtils 还能把内容拷入其他的 Writer 中,如 IOUtils.copy(inputStream, new StringWriter())。

5. Google guava 的  CharStreams 方法
 1package cc.unmi.test;
 2
 3import java.io.*;
 4
 5import com.google.common.io.CharStreams;
 6
 7/**
 8 * 
 9 * @author Unmi
10 * @Creation date: 2013-02-01
11 */
12public class Test {
13
14    /**
15     * @throws IOException 
16     */
17    public static void main(String[] args) throws IOException {
18        InputStream inputStream = new FileInputStream("d:/sample.txt");
19        String text = CharStreams.toString(new InputStreamReader(inputStream, "UTF-8"));
20        System.out.println(text);
21    }
22}

CharSteams 不是直接作用在 InputSteam 上的,还要靠 InputStreamReader 拱个桥。

6. JDK 7 的 NIO readAllBytes
 1package cc.unmi.test;
 2
 3import java.io.IOException;
 4import java.nio.file.*;
 5
 6/**
 7 * 
 8 * @author Unmi
 9 * @Creation date: 2013-02-01
10 */
11public class Test {
12
13    /**
14     * @throws IOException 
15     */
16    public static void main(String[] args) throws IOException {
17        byte[] bytes = Files.readAllBytes(Paths.get("d:/sample.txt"));
18        String text = new String(bytes);
19        System.out.println(text);
20    }
21}

这让我们相信 JDK  一直还有人在管,虽然不可能象动态语言的方法那么快捷,上面的  readAllBytes 在处理大文件时肯定会很被动的。而 Files.readAllLines 会把文件的内容读入一个 List<String> 对象中,往内存不断放东西就得掂量下内存会不会被爆。在 java.nio.file.* 还有很多新事物可供发掘。

参考: 1. 5 ways to convert InputStream to String in Java 永久链接 https://yanbin.blog/java-convert-inputstream-to-string/, 来自 隔叶黄莺 Yanbin's Blog
[版权声明] 本文采用 署名-非商业性使用-相同方式共享 4.0 国际 (CC BY-NC-SA 4.0) 进行许可。