读取txt文件内容到String

package com.example.demo.util;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;

/**
 * 读取txt文件内容到String
 */
public class ReadFileToString {
    public static void main(String[] args) throws Exception {
        readFileToString();
    }

    public static void readFileToString(){
        File file = new File("D:\\test\\10.txt");
        try (FileReader reader = new FileReader(file);
             BufferedReader br = new BufferedReader(reader)){

             StringBuilder sb = new StringBuilder();
             String s = "";
             while((s = br.readLine()) != null){
                 sb.append(s + "\n");
             }
             br.close();
            System.out.println(sb.toString());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
相关推荐
©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页