i m learning file input output and i m having a problem in it.a.txt have some text and when it read and print the world there is'?'mark at the end.. how to remove it.
import java.io.*;
class fRead{
public static void main(String args[])throws IOException
{
FileInputStream fin=new FileInputStream("a.txt");
int i=0;
while(i!=-1){
i=fin.read();
System.out.print((char)i);
}
fin.close();
}
}
the result in CMD:-
G:\file>javac fRead.java
G:\file>java fRead
VINAYAK COMPUTER ACADEMY?
the***'?'*** in the end is not in the end of file.
This problem happens because you print -1
that you get from the read()
after converting it to char
, even though the loop should stop without printing anything when -1
is returned.
You can fix it by combining the assignment with the check for negative one:
while ((i = fin.read()) != -1) {
System.out.print((char)i);
}