inputstreamreader读取文件_java读取字符串中每一个字符

inputstreamreader读取文件_java读取字符串中每一个字符二.字符流1.单个字符读取publicstaticvoidmain(String[]args){ try{ InputStreamReaderin=newInputStreamReader( newFileInputStream(“D:\\bf\\Desktop\\test.txt”),”UTF-8″); intn; while((n…

大家好,又见面了,我是你们的朋友全栈君。如果您正在找激活码,请点击查看最新教程,关注关注公众号 “全栈程序员社区” 获取激活教程,可能之前旧版本教程已经失效.最新Idea2022.1教程亲测有效,一键激活。

Jetbrains全系列IDE稳定放心使用

二.字符流
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次数,提升效率。

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

发布者:全栈程序员-用户IM,转载请注明出处:https://javaforall.cn/189346.html原文链接:https://javaforall.cn

【正版授权,激活自己账号】: Jetbrains全家桶Ide使用,1年售后保障,每天仅需1毛

【官方授权 正版激活】: 官方授权 正版激活 支持Jetbrains家族下所有IDE 使用个人JB账号...

(0)
blank

相关推荐

发表回复

您的电子邮箱地址不会被公开。

关注全栈程序员社区公众号