java讀取文本文件內容

示例代碼如下:

public static void main(String[] args) {
    String path = "D:/demo.txt";
    String line = null;
    String content = ""; // 文件內容
    BufferedReader br = null;
    try {
        // br = new BufferedReader(new FileReader(path));
        br = new BufferedReader(new FileReader(new File(path))); // 與上等效

        while (null != (line = br.readLine())) {
            System.out.println(line);
            content += line + "\n";
        }
        br.close();
        System.out.println("--------------風騷分隔線--------------");
        System.out.println(content);
    } catch (Exception e) {
        e.printStackTrace();
    }
}

打印執行結果:

hello, world!!!


    hello, world!!!
--------------風騷分隔線--------------
hello, world!!!


    hello, world!!!


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章