JAVA字符流InputStreamReader读取文本

二.字符流
1.单个字符读取

public static void main(String[] args){
		try {
			InputStreamReader in = new InputStreamReader(
					new FileInputStream("D:\\bf\\Desktop\\test.txt"), "UTF-8");
			int n ;
			while((n = in.read()) != -1){
				System.out.print((char)n); 
			}
			in.close();
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		 
	}

单个字符读取结果
2.按行读取,利用BufferedReader对象提供的readLine()方法

public static void main(String[] args) {
		BufferedReader reader=null;
		try {
			InputStreamReader read = new InputStreamReader(new FileInputStream("D:\\bf\\Desktop\\test.txt"), "UTF-8");
			reader = new BufferedReader(read);
			String line=null;
						
			while((line =reader.readLine()) != null){
				System.out.println(line);						
			}			
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {			
			e.printStackTrace();
		}finally {
			if (reader !=null) {
				try {
					reader.close();
				} catch (IOException e) {					
					e.printStackTrace();
				}
			}
		}
		
	}

按行读取结果
InputStreamReader是一个一个字符读取的,每次读取都会执行一次IO,IO操作很浪费时间,这就导致程序效率降低,而BufferedReader可以一次读取大量的数据,大大减少了IO次数,提升效率。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值