在劫

吾生也有涯,而知也无涯 。

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

从字符输入流中读取文本,缓冲各个字符,从而实现字符、数组和行的高效读取。

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();
	}

}
posted on 2018-07-08 13:58  长嘴大耳怪  阅读(120)  评论(0编辑  收藏  举报