从.txt文档逐行读入数据,用到FileReader和BufferedReader类:
import java.io.IOException; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.BufferedReader; public class ReadLine_Test { public static void main(String[] args) throws IOException{ String FilePath = "e:/data.txt"; FileReader fr = new FileReader(FilePath); //建立FileReader对象,并实例化为fr BufferedReader br = new BufferedReader(fr); //建立BufferedReader对象,并实例化为br StringBuffer sBuffer = new StringBuffer(); String Line = br.readLine(); //从文本中读取一行字符串 int i = 1; while(Line != null){ System.out.println("Line"+i+":"+Line); sBuffer.append(Line); sBuffer.append(" "); Line = br.readLine(); //从文本中继续读取一行字符串 i = i+1; } if(br != null){ br.close(); //关闭BufferedReader对象 } if(fr != null){ fr.close(); //关闭文件 } } }