文件io方法

1)
File file = new File ("hello.txt");
FileInputStream in=new FileInputStream(file);
InputStreamReader inReader=new InputStreamReader(in);
BufferedReader bufReader=new BufferedReader(inReader);

2)
FileInputStream in=null;
File file = new File ("hello.txt");
in=new FileInputStream(file);
BufferedReader bufReader=new BufferedReader(new InputStreamReader(in));

3)
File file = new File ("hello.txt");
BufferedReader bufReader=new BufferedReader(new InputStreamReader(new FileInputStream(file)));

上述两种写法的微小区别:
a)第二种方式中把“FileInputStream in=null;”定义单独放在开始处,说明下面应该还有要用到in对象变量的地方;(BufferedReader处用了)

b)第二种方式没有定义InputStreamReader的对象变量,直接在BufferedReader的构造函数中new一个,
这种方式与第一种方式的主要区别:InputStreamReader对象只使用一次!

这对于在这里只需要使用一次这个InputStreamReader对象的应用来说更好;无需定义InputStreamReader的对象变量,接收由new返回的该对象的引用,因为下面的程序中不需要这个InputStreamReader的对象变量,所以无需定义;所以这种情况下,第二种方式比第一种更好一些。

c)第三种方式中,典型的三层嵌套委派关系,清晰看出Reader的委派模式(《corejava》12章有图描述该委派关系),FileInputStream和InputStreamReader都没有定义变量,new生成的对象都只是使用一次。

d)三种方式的区别也就在于FileInputStream和InputStreamReader对象是否都只使用一次,是否需要定义它们的对象变量,以及个人的编码习惯。

e)但是要注意异常处理,FileInputStream(file)会抛出NotFileFoundException,如果采用surround方式
(try&catch)处理,应该用第二种方式,这样可以用System.out.println提示文件未找到;
当然在函数名后使用throws Exception,然后用第三种方式也行,但似乎这适合有用户界面的情况,把异常抛出在客户端在处理。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值