【问题标题】:How to read bytes from a file to a byte[] array? [duplicate]如何从文件中读取字节到 byte[] 数组? [复制]
【发布时间】:2016-03-07 09:32:28
【问题描述】:

我正在编写一个 Java 程序,它使用 RSA 加密给定文本,并将加密的字节(字节 [] 数组)保存在 .txt 文件中。有一个单独的解密程序可以读取这些字节。现在我想将相同的字节读入解密程序中的 byte[] 中。如何使用 Java 来做到这一点?

BufferedReader brip = new BufferedReader(new FileReader("encrypted.txt"));
Strings CurrentLine = brip.readLine();
byte[] b = sCurrentLine.getBytes();

这就是我从文件中读取数据的方式。但这是错误的,因为它将 sCurrentLine 变量中的字节再次转换为字节。

【问题讨论】:

  • 你有没有尝试过阅读它?请通过显示示例代码来演示解决问题的一些尝试。如果您不知道从哪里开始,Google 总是一个不错的选择。
  • 向我们展示你到目前为止所做的事情。
  • 这里一切都错了。加密数据不是文本;不应存储在名为 .txt 的文件中;不包含行;并且无法使用Reader. 读取使用InputStream.

标签: java file byte bytearray


【解决方案1】:

在 Java 7 中,您可以使用 Files 类的 readAllBytes() 方法。见下文:

Path fileLocation = Paths.get("C:\\test_java\\file.txt");
byte[] data = Files.readAllBytes(fileLocation);

还有很多其他方法可以做到这一点,请参阅 herehere

【讨论】:

  • 这只适用于较小的文件。
【解决方案2】:

这段代码对我有用,在一个 android 项目中,所以希望它对你有用。

 private byte[] getByte(String path) {
    byte[] getBytes = {};
    try {
        File file = new File(path);
        getBytes = new byte[(int) file.length()];
        InputStream is = new FileInputStream(file);
        is.read(getBytes);
        is.close();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return getBytes;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-01-29
    • 2023-03-08
    • 2021-07-21
    • 1970-01-01
    • 2011-12-04
    • 1970-01-01
    • 2019-02-19
    • 1970-01-01
    相关资源
    最近更新 更多