Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to stop Scanner changing bytes when inputing data from file in Java?

I am using the Scanner utility in Java to input data from a file like so:

        File file = new File("mazes.txt");
        Scanner scan = new Scanner(file);  
        scan.useDelimiter("__________\n");  
        String record = scan.next();

but it is changing certain bytes to other bytes. For example, where the record string should be a byte with hexadecimal value 80, Scanner seems to turn this into a byte with a hex value of ac. How can I input records from the file without any switching of the bytes like this?

like image 960
flea whale Avatar asked Aug 08 '26 17:08

flea whale


1 Answers

From the documentation of the constructor:

Bytes from the file are converted into characters using the underlying platform's default charset.

If your file has another encoding, you must use (e.g.):

 Scanner scan = new Scanner(file,"UTF-8");  

or

 Scanner scan = new Scanner(file,"ISO8859-1");

etc.

like image 115
Daniel Avatar answered Aug 10 '26 07:08

Daniel



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!