Java 如何从文件中读取字节到 byte[] 数组?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/34054655/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 15:16:14  来源:igfitidea点击:

How to read bytes from a file to a byte[] array?

javafilebytebytearray

提问by daipayan

I am writing a Java program which encrypts a given text using RSA, and saves the encrypted bytes(byte[] array) in a .txt file. There is a separate decryption program which reads these bytes. Now I want to read the same bytes into a byte[] in to the decryption program. How can this be done using Java?

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

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

This is how I have been reading the data from the file. But it's wrong because it converts the bytes in sCurrentLine variable into again bytes.

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

回答by Raf

In Java 7 you can use the readAllBytes()method of Files class. See below:

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

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

There are many other ways to do it see hereand here

还有很多其他方法可以看到这里这里

回答by Shahzad Afridi

This code worked for me, in an android project so hopefully, it will work for you.

这段代码对我有用,在一个 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;
}