user14252942
user14252942

Reputation:

File Reader prints out "?" instead of file

Whenever I hit compile I get "?" as an output. No errors or anything, just the question mark.
Here's my code:

import java.io.*;
    
public class FileReaderExample {
    
    public static void main(String[] args) {        
        try {
            FileReader fileReader = new FileReader("path to my text file");
            int data = fileReader.read();
            while (data != -1) {
                data = fileReader.read();
            }
            System.out.print((char)data); 
        } catch (Exception e) {
            System.err.println("There's been an error.");
        }
    }
}

Upvotes: 0

Views: 86

Answers (1)

Henry
Henry

Reputation: 43758

When your program reaches System.out.print((char)data); the value of data is -1. This is not a printable character hence the ?.

Upvotes: 7

Related Questions