Java Reader,读取文本文件的方法

时间:2013-05-19 21:14:47

标签: java bufferedreader

我有一个名为test.txt的文本文件,其中包含hello一词。我试图使用Reader.read()方法读取它并将内容打印到控制台。然而,当我运行它时,我只是将数字104打印在控制台上而没有其他内容(即使我将文本更改为更多/更少的字符,我也会打印相同的数字)。任何想法为什么它以这种方式表现,如何修改现有代码以在控制台上作为字符串打印test.txt的内容?这是我的代码:

public static void spellCheck(Reader r) throws IOException{
    Reader newReader = r;
    System.out.println(newReader.read());
}

和我用来测试上面的主要方法:

public static void main (String[] args)throws IOException{
    Reader test = new BufferedReader(new FileReader("test.txt"));
    spellCheck(test);
}

2 个答案:

答案 0 :(得分:4)

read()正在完成它的supposed to

  

读取单个字符。此方法将阻塞,直到字符可用,发生I / O错误或到达流的末尾。

(强调补充)

相反,您可以在循环中调用BufferedReader.readLine()

答案 1 :(得分:2)

the javadoc所示,read()方法读取单个char,并将其作为int返回(为了能够返回-1以指示流的结束)。要将int打印为char,只需将其转换为:

int c = reader.read();
if (c != -1) {
    System.out.println((char) c);
}
else {
    System.out.println("end of the stream");
}

要读取所有内容,请循环直到获得-1,或逐行读取,直到获得null。

相关问题