黑马程序员技术交流社区

标题: 如何从文本中读取在控制台显示?求大神指教,帮我简化代码 [打印本页]

作者: 闭关修行小和尚    时间: 2016-1-2 23:52
标题: 如何从文本中读取在控制台显示?求大神指教,帮我简化代码
public static void main(String[] args) {
                // 封装数据源
                BufferedReader br = null;
                try {
                        br = new BufferedReader(new FileReader("Test1.java"));
                        String line = null;
                        while ((line = br.readLine()) != null) {
                                System.out.println(new String(line));
                        }
                } catch (Exception e) {
                        e.printStackTrace();
                } finally {
                        try {
                                br.close();
                        } catch (IOException e) {
                                e.printStackTrace();
                        }

                }
        }


作者: 549208564    时间: 2016-1-3 02:01
好象JDK5.0还是7.0来着,可以将关闭流写入try()中,如         
BufferedReader br = null;                 
try(br = new BufferedReader(new FileReader("Test1.java"));) {                        
   String line = null;                        
while ((line = br.readLine()) != null) {                              
  System.out.println(new String(line));                       
  }                 
} catch (Exception e) {                       
  e.printStackTrace();               
}
要不就写一个方法,传入一个输入流,在到main方法中调中
在怎么简化就不知道了
作者: 江江会回来的    时间: 2016-1-5 01:51

public static void main(String[] args) {
                // 封装数据源
                BufferedReader br = null;                StringBuffer sb = null;
                try {
                        br = new BufferedReader(new FileReader("Test1.java"));
                        sb = = new StringBuffer();
                        String line = null;
                        while ((line = br.readLine()) != null) {
                                sb.append(line);
                        }
                        System.out.println(line.tostring());
                } catch (Exception e) {
                        e.printStackTrace();
                } finally {
                        try {                               if(null != br)
                                br.close();
                        } catch (IOException e) {
                                e.printStackTrace();
                        }

                }
        }






欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) 黑马程序员IT技术论坛 X3.2