user1894469
user1894469

Reputation: 143

Java Reader, read method for text file

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);
}

Upvotes: 0

Views: 1680

Answers (2)

JB Nizet
JB Nizet

Reputation: 692171

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.

Upvotes: 2

SLaks
SLaks

Reputation: 888187

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.

Upvotes: 4

Related Questions