简体   繁体   中英

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!

we were tasked with storing an encrypted password into a byte[], write the byte[] to file, then read the byte[] back in.

A java.util.Scanner is not necessary for this task.

You can write a byte[] using a OutputStream and read a byte[] using a InputStream .

There are short-cut methods for reading and writing byte[] arrays as well in the Files utility methods:

  • public static Path write(Path path, byte[] bytes, OpenOption... options) throws IOException
  • public static byte[] readAllBytes(Path path) throws IOException

java.util.Scanner is a 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 and return a byte as a raw byte directly. Rather, it 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).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM