Java:将文本文件的内容打印到屏幕 [英] Java: print contents of text file to screen

查看:133
本文介绍了Java:将文本文件的内容打印到屏幕的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个名为 foo.txt 的文本文件,其内容如下:

I have a text file named foo.txt, and its contents are as below:


这个

this

text

如何在Java 7中将这个确切的文件打印到屏幕上?

How would I print this exact file to the screen in Java 7?

推荐答案

在Java 7之前:

 BufferedReader br = new BufferedReader(new FileReader("foo.txt"));
 String line = null;
 while ((line = br.readLine()) != null) {
   System.out.println(line);
 }




  • 添加异常处理

  • 添加关闭流

  • 从Java 7开始,不需要关闭流,因为它实现了 autocloseable

    Since Java 7, there is no need to close the stream, because it implements autocloseable

    try (BufferedReader br = new BufferedReader(new FileReader("foo.txt"))) {
       String line = null;
       while ((line = br.readLine()) != null) {
           System.out.println(line);
       }
    }
    

    这篇关于Java:将文本文件的内容打印到屏幕的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆