0

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);
}
2
  • @peter.murray.rust: no, it's returning a char as an int, or -1, as every Reader. Commented May 19, 2013 at 21:20
  • You're reading one character and you're printing one character. The code is working as designed. What's the question? Commented May 19, 2013 at 23:25

2 Answers 2

4

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for the link, the answer was staring right at me. Unfortunately I could only select one as the answer, but your help and prompt reply is appreciated.
2

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.

2 Comments

How do I read line by line? My method is taking (Reader r) as a parameter, and I do not want to change that. Then I cannot say BufferedReader newReader = r as that gives me incompatible type. But as far as I can tell from the docs, Reader does not have a readLine() method.
BufferedReader is the class allowing to read line by line. So if that's what you want to do, wrap the Reader into a BufferedReader in your method. But you don't need to read line by line to read everything. You can simply use this read method (for better performance) until it returns -1.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.