I know the correct approach is
BufferedReader br = new BufferedReader(FileReader(file));
but I checked in the Java API the methods of FileReader class and it has a read() method that return the character read. But it’s not working for me. I’m reading a file that contains this line of text: “I’m reading a file”, and printing it to the screen, but when I run program it prints the equivalent ASCII code for each character.
This is my code:
String lectura = "";
try{
lectura = String.valueOf(fr.read());
} catch(IOException ioex){
ioex.printStackTrace();
}
while((Integer.parseInt(lectura)) != -1){
System.out.print(lectura);
try{
lectura = String.valueOf(fr.read());
} catch(IOException ioex){
ioex.printStackTrace();
}
}
What is happening is this –
fr.read() is returning an integer and not a character, although that integer returned is the equivalent ASCII code for that character.
When you call String.valueOf() on that integer, the String.valueOf(int i) method gets called, instead of the String.valueOf(char c) method which you are expecting to get called, and therefore it returns the ASCII value as a string, instead of the character value as a string.
So instead, try