Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Can I read a byte array from file using scanner?

Java.util.scanner can read a variety of data types in including Byte, but what about byte[]? I’ve searched for information on Oracle’s website as well as other websites, but I’m having trouble finding information on scanning byte[], so I’m wondering if it’s even possible. I am taking a Java course and we were tasked with storing an encrypted password into a byte[], write the byte[] to file, then read the byte[] back in. Given the requirements of this task, I cannot convert the byte[] to a string, it has to remain a byte[]. — Thank you in advance for your suggestions!

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

java.util.Scanner is text scanner. That is, the bytes it reads from the input (stdin, say) is expected to comply to a certain charset, usually UTF-8.

In the case of nextByte(), it doesn’t read a byte as a raw byte directly, rather reads a text and returns the next token as a byte. Here’s what the documentation of java.util.Scanner.nextByte(radix) says (emphasis added by me):

If the next token matches the Integer regular expression defined above then the token is converted into a byte value as if by removing all locale specific prefixes, group separators, and localespecific suffixes, then mapping non-ASCII digits into ASCIIdigits via Character.digit, prepending anegative sign (-) if the locale specific negative prefixes and suffixes were present, and passing the resulting string to Byte.parseByte with thespecified radix.

So, what you will have to do is to read as string and convert it to bytes using the right charset (UTF-8, usually).

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading