简体   繁体   English

如何读取文本文件并将其打印到控制台窗口? 爪哇

[英]How do you read a text file and print it to the console window? Java

I would like to read an entire text file and store its entire contents into a single string. 我想读取整个文本文件,并将其全部内容存储到单个字符串中。 Then I would like to print the string to the console window. 然后,我想将字符串打印到控制台窗口。 I tried this: 我尝试了这个:

import java.util.Scanner;
import java.io.*;

public class WritingTextFiles{

    public static void main (String [] args) throws IOException{
        FileWriter fw= new FileWriter("testing.txt");  
        Scanner in= new Scanner (System.in);
        String testwords=in.nextLine();  
        fw.write(testwords);  
        BufferedReader r = new BufferedReader( new FileReader( "testing.txt" ) );  
        System.out.print(r);  
        fw.close();  
    }
}

The only thing that is printed to the console window is java.io.BufferedReader@18fb397. 打印到控制台窗口的唯一内容是java.io.BufferedReader@18fb397。

Can anyone explain this to a newbie like me? 任何人都可以向像我这样的新手解释吗? I have very little experience but I am certainly willing to learn. 我的经验很少,但我当然愿意学习。 I am open to any and all suggestions. 我愿意接受任何建议。 Thanks in advance! 提前致谢!

The reason that java.io.BufferedReader@18fb397 is printed to the console is because you give the reference of the buffered reader as an argument to print, and not the string you want to print. 将java.io.BufferedReader@18fb397打印到控制台的原因是,您将缓冲读取器的引用作为要打印的参数而不是要打印的字符串作为参数。

BufferedReader r = new BufferedReader( new FileReader( "testing.txt" ) );
System.out.print(r);

should be: 应该:

BufferedReader r = new BufferedReader( new FileReader( "testing.txt" ) );
String s = "", line = null;
while ((line = r.readLine()) != null) {
    s += line;
}
System.out.print(s);

Notice we actually read the lines of the file and store it in a temporary variable, then we append this variable to s. 请注意,我们实际上是读取文件的各行并将其存储在一个临时变量中,然后将此变量附加到s上。 Then we print s, and not the BufferedReader. 然后我们打印s,而不是BufferedReader。

On a final note, it is wise to close a file when your done, you do call fw.close(), but you should have called it directly after writing the testwords. 最后要注意的是,完成后关闭文件是明智的,您可以调用fw.close(),但是您应该在编写测试词后直接调用它。 This is to make sure that the FileWriter has actually written the string. 这是为了确保FileWriter实际上已经写入了字符串。

If it's a relatively small file, a one-line Java 7+ way to do this is: 如果文件相对较小,则可以通过单行Java 7+实现:

System.out.println(new String(Files.readAllBytes(Paths.get("testing.txt"))));

If you just want to read it into a String, that's also simple: 如果您只想将其读取为字符串,这也很简单:

String s = new String(Files.readAllBytes(Paths.get("testing.txt")));

See https://docs.oracle.com/javase/7/docs/api/java/nio/file/package-summary.html for more details. 有关更多详细信息,请参见https://docs.oracle.com/javase/7/docs/api/java/nio/file/package-summary.html

Cheers! 干杯!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM