如何获取 Android 中的文件字节

How to get byte of file in Android

在我的应用程序中,我想读取文件的前 16 个字符
我写了下面的代码,但是对于这个 byte[ ] 只是告诉我 43!
我想先显示 16 个字节的字符 .

我的代码:

String inputFile = getRootDirPath(context) + "/" + "girnmqlyv0.pdf";
File file = new File(inputFile);
                try {
                    byte[] fileBye = FileUtils.readFileToByteArray(file);
                    Log.e("FileByte", ""+fileBye[16]);
                } catch (IOException e) {
                    e.printStackTrace();
                }

logcat 中显示此消息:

E/FileByte: 43

如何获取文件的第 16 个字符?

要从前 16 个字节创建一个字符串,请使用它而不是 "+fileBye[16]:

Log.e("FileByte", new String(fileBye, 0, 16));

请注意,这会根据默认字符编码将前 16 字节 转换为字符串,即 Android 上的 UTF-8。如果文件中的文本包含非 ASCII 字符,则 16 个字节将不会转换为 16 个字符。


提取前16个字节作为字节数组,可以使用:

byte[] first16 = Arrays.copyOfRange(fileBye, 0, 16);

或者您可以只读取前 16 个字节,而不是整个文件:

byte[] first16 = new byte[16];
try (FileInputStream in = new FileInputStream(inputFile)) {
    in.read(first16);
}

像这样定义数组的大小byte[] bytes = new byte[size];

在你的例子中,尺寸是 16