Java中快速把InputStream转化为String

早上看到占小狼的博客的微信公众号推送了一篇名为"Stack Overflow上200万阅读的一个提问:Java中怎么快速把InputStream转化为String"的文章,正好感兴趣就去看了下Stack Overflow的这个问题—— How do I read / convert an InputStream into a String in Java?

How do I read / convert an InputStream into a String in Java?

占小狼的博客发布的测试结果截图

感兴趣的童鞋可以自己去Stack Overflow看看,当然也可以当个懒人看占小狼的博客的文章总结后的,我这个超级懒人就只写了测试结果最好的ByteArrayOutputStreamand read (JDK)的Demo,留着备用。话不多说,代码留下:

package top.lzzly.FileDemo;

import java.io.*;
import org.apache.log4j.Logger;

public class FileDemo {
    private static Logger mLogger = Logger.getLogger("FileDemo");

    public static void main(String args[]) {
        String filePath = "/Users/lzz/Downloads/lzm_longvideo_platform.sql";
        String txt = readFile(filePath);
        mLogger.info(txt);
    }

    /**
     * 读取File工具类,返回String
     * @param filePath 文件路径
     * @return
     */
    private static String readFile(String filePath){
        try{
            File file = new File(filePath);
            FileInputStream fis = new FileInputStream(file);
            String txt = convertStreamToString(fis);
            return txt;
        }catch (Exception e){
            System.out.println(e.getMessage());
        }
        return null;
    }

    /**
     * InputStream转String工具类,返回String
     * @param inputStream
     * @return
     */
    private static String convertStreamToString(InputStream inputStream) throws IOException {
        ByteArrayOutputStream result = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int length;
        while ((length = inputStream.read(buffer)) != -1) {
            result.write(buffer, 0, length);
        }// StandardCharsets.UTF_8.name() > JDK 7
        return result.toString("UTF-8");
    }

}

你可能感兴趣的:(Java中快速把InputStream转化为String)