java 窗口 获取输入,如何读取文本文件并将其打印到控制台窗口? 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.

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.

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. Then we print s, and not the 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. This is to make sure that the FileWriter has actually written the string.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值