从字符输入流中读取文本,缓冲各个字符,从而实现字符、数组和行的高效读取。
public class BufferedReaderJava {
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
String sPath1 = "d:" + File.separator + "javatest" + File.separator + "CollectionTest1.java";
BufferedReader r = new BufferedReader(new FileReader(new File(sPath1)));
char[] ch = new char[1024];
int result = 0;
//确认流是否准备好
if(r.ready()) {
//读取数据
while((result = r.read(ch)) != -1) {
System.out.println(new String(ch, 0, result));
}
}
r.close();
}
}
使用readLine()方法每次读取一行
public class BufferedReaderJava {
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
String sPath1 = "d:" + File.separator + "javatest" + File.separator + "CollectionTest1.java";
BufferedReader r = new BufferedReader(new FileReader(new File(sPath1)));
String str = null;
while((str = r.readLine()) != null) {
System.out.println(str);
}
r.close();
}
}
public class BufferedReaderJava {
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
String sPath1 = "d:" + File.separator + "javatest" + File.separator + "CollectionTest1.java";
BufferedReader r = new BufferedReader(new FileReader(new File(sPath1)));
//String str = null;
int result = 0;
//这里输出的时候每行首字符丢失,因为先read()了一个字符,然后输出的时候接下来readLine()的部分
while((result = r.read()) != -1) {
System.out.println(r.readLine());
}
r.close();
}
}