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 :
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).