I have a text file called test.txt with the word hello. I am trying to read it using Reader.read() method and print the contents to console. However when I run it I am just getting the number 104 printed on console and nothing else (I get the same number printed even if I change the text to more/less characters). Any ideas why it is behaving this way and how can I modify this existing code to print the contents of test.txt as a string on console? Here is my code:
public static void spellCheck(Reader r) throws IOException{
Reader newReader = r;
System.out.println(newReader.read());
}
and my main method I am using to test the above:
public static void main (String[] args)throws IOException{
Reader test = new BufferedReader(new FileReader("test.txt"));
spellCheck(test);
}
read()
is doing exactly what it's supposed to :
Reads a single character. This method will block until a character is available, an I/O error occurs, or the end of the stream is reached.
(emphasis added)
Instead, you can call BufferedReader.readLine()
in a loop.
As the javadoc indicates, the read() method reads a single char, and returns it as an int (in order to be able to return -1 to indicate the end of the stream). To print the int as a char, just cast it:
int c = reader.read();
if (c != -1) {
System.out.println((char) c);
}
else {
System.out.println("end of the stream");
}
To read everything, loop until you get -1, or read line by line until you get null.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.