示例代碼如下:
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!!!