Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

While reading from file in java, input is prefixed by two junk characters

Tags:

java

file

utf-8

FileInputStream fin = new FileInputStream("D:\\testout.txt");    
BufferedInputStream bin = new BufferedInputStream(fin);    
int i;    
while((i = bin.read())!=-1) {    
    System.out.print((char)i);    
}    

bin.close();    
fin.close();    

output: ÿþGreat

I have checked the file testout.txt, it contains only one word i.e, Great.

like image 672
kartik singh rajput Avatar asked Dec 31 '25 18:12

kartik singh rajput


1 Answers

When you're using text, you should use a Reader. eg.

try(
    BufferedReader reader = Files.newBufferedReader(
        Paths.get("D:\\testout.txt"), 
        StandardCharsets.UTF_8)
    ){
    int i;    
    while((i = reader.read())!=-1) {    
        System.out.print((char)i);    
    }  
}
like image 192
matt Avatar answered Jan 03 '26 07:01

matt



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!