[英]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[]? Java.util.scanner可以读取包括Byte在内的多种数据类型,但是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.
我已经在 Oracle 的网站以及其他网站上搜索了信息,但是我无法找到有关扫描 byte[] 的信息,所以我想知道它是否可能。 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[].
我正在参加 Java 课程,我们的任务是将加密密码存储到 byte[] 中,将 byte[] 写入文件,然后将 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.
我们的任务是将加密密码存储到 byte[] 中,将 byte[] 写入文件,然后将 byte[] 读回。
A java.util.Scanner
is not necessary for this task.此任务不需要
java.util.Scanner
。
You can write a byte[]
using a OutputStream
and read a byte[]
using a InputStream
.您可以使用
OutputStream
写入byte[]
并使用InputStream
读取byte[]
。
There are short-cut methods for reading and writing byte[]
arrays as well in the Files
utility methods:在
Files
实用程序方法中也有读写byte[]
arrays 的快捷方法:
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. java.util.Scanner
是一款文本扫描仪。 That is, the bytes it reads from the input (stdin, say) is expected to comply to a certain charset, usually UTF-8.也就是说,它从输入(例如标准输入)读取的字节应该符合某个字符集,通常是 UTF-8。
In the case of nextByte()
, it doesn't read and return a byte as a raw byte directly.在
nextByte()
的情况下,它不会直接读取并返回一个字节作为原始字节。 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):这是
java.util.Scanner.nextByte(radix)
的文档所说的(重点由我添加):
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.
如果下一个标记与上面定义的 Integer 正则表达式匹配,则该标记被转换为字节值,就像通过删除所有区域设置特定前缀、组分隔符和区域设置特定后缀,然后通过 Character.digit 将非 ASCII 数字映射为 ASCII 数字,前置如果存在特定于语言环境的负前缀和后缀,则为负号 (-),并将结果字符串传递给具有指定基数的 Byte.parseByte。
So, what you will have to do is to read as string and convert it to bytes using the right charset (UTF-8, usually).因此,您需要做的是读取字符串并使用正确的字符集(通常为 UTF-8)将其转换为字节。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.