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

时间:2018-02-13 16:47:14   收藏:0   阅读:3972
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;
    }
}

 

评论(0
© 2014 mamicode.com 版权所有 京ICP备13008772号-2  联系我们:gaon5@hotmail.com
迷上了代码!