Java如何读取文本文件

2014-11-16 20:40:35 · 作者: · 浏览: 45

  下面的代码是读取文本文件的例子,程序会读取text.txt文件,并将它的内容显示出来。


  1 import java.io.BufferedReader;


  2 import java.io.File;


  3 import java.io.FileReader;


  4 import java.io.FileNotFoundException;


  5 import java.io.IOException;


  6


  7 public class ReadTextFileExample


  8 {


  9 public static void main(String[] args)


  10 {


  11 File file = new File("test.txt");


  12 StringBuffer contents = new StringBuffer();


  13 BufferedReader reader = null;


  14


  15 try


  16 {


  17 reader = new BufferedReader(new FileReader(file));


  18 String text = null;


  19


  20 // repeat until all lines is read


  21 while ((text = reader.readLine()) != null)


  22 {


  23 contents.append(text)


  24 .append(System.getProperty(


  25 "line.separator"));


  26 }