« | August 2025 | » | 日 | 一 | 二 | 三 | 四 | 五 | 六 | | | | | | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 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();} |
|
|