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;
    }
}

轉載於:https://www.cnblogs.com/hedongfei/p/10552192.html


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM