Java读取一个文本文件拼接成一个字符串(readFileToString)

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;

import org.junit.Test;

public class Demo {// 使用示例
    @Test
    public void testName1() throws Exception {
        String filePath = "D:\\测试数据\\测试数据.json";

        String jsonString = readFileToString(filePath);

        System.out.println(jsonString);

        System.out.println("done.....");
    }

    public static String readFileToString(String path) {
        // 定义返回结果
        String jsonString = "";

        BufferedReader in = null;
        try {
            in = new BufferedReader(new InputStreamReader(new FileInputStream(new File(path)), "UTF-8"));// 读取文件  
            String thisLine = null;
            while ((thisLine = in.readLine()) != null) {
                jsonString += thisLine;
            }
            in.close();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException el) {
                }
            }
        }

        // 返回拼接好的JSON String
        return jsonString;
    }
}
posted @ 2019-03-18 14:56  何年何月生  阅读(3686)  评论(0编辑  收藏  举报