本站首页    管理页面    写新日志    退出


«August 2025»
12
3456789
10111213141516
17181920212223
24252627282930
31


公告

戒除浮躁,读好书,交益友


我的分类(专题)

日志更新

最新评论

留言板

链接

Blog信息
blog名称:邢红瑞的blog
日志总数:523
评论数量:1142
留言数量:0
访问次数:9697066
建立时间:2004年12月20日




[编程感想]使用for循环和while循环的关系
原创空间,  软件技术,  电脑与网络

邢红瑞 发表于 2007/6/2 14:20:07

有人在QQ群里,做读取Reader内容,我给出了以下的写法, try {   File readfile = new File(FileName);   if (readfile.exists()) {    InputStreamReader fr = new InputStreamReader(      new FileInputStream(FileName), "UTF-8");    BufferedReader br = new BufferedReader(fr);    String s;    StringBuffer sb = new StringBuffer();    while ((s = br.readLine()) != null) {     sb.append(s + "\n");    }                         }  catch (FileNotFoundException e) {   e.printStackTrace();   /* 文件不存在,返回null */   return null;  } catch (IOException e) {   e.printStackTrace();   return null;  }想了想有一个问题,Effective Java上说最小化局部变量作用域,c语言强制规定局部变量必须在块的开头声明,我也是c程序转过来的,以后的java和c++可以在代码任何地方声明变量,最小化局部变量的最有效方式是在它第一次声明时使用,循环是最小化变量作用域的特别场所,当循环的变量在循环结束后不再使用,使用for比while要好。于是改为如下的BufferedReader reader = .... for (String line = reader.readLine(); line != null; line = reader.readLine()) {     .... }想了想这样也行的BufferedReader reader = ...;while (true){  String line = reader.readLine();  if (line==null)    break;  ...}其实idea是蛮聪明的,"ctrl-alt-t" - "a"答案就出来了。这段代码应该是最好的try{  BufferedReader reader = ...  try  {    for (String line; (line = reader.readLine()) != null; )    {      ...    }    return something;  }  finally  {    reader.close();  }}catch (Throwable ex){  System.out.println("problem");  ex.printStackTrace();}


阅读全文(8033) | 回复(1) | 编辑 | 精华
 



发表评论:
昵称:
密码:
主页:
标题:
验证码:  (不区分大小写,请仔细填写,输错需重写评论内容!)



站点首页 | 联系我们 | 博客注册 | 博客登陆

Sponsored By W3CHINA
W3CHINA Blog 0.8 Processed in 0.313 second(s), page refreshed 144777222 times.
《全国人大常委会关于维护互联网安全的决定》  《计算机信息网络国际联网安全保护管理办法》
苏ICP备05006046号