英文:
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[] fileByte = FileUtils.readFileToByteArray(file);
Log.e("FileByte", "" + (char)fileByte[16]);
} catch (IOException e) {
e.printStackTrace();
}
在 logcat
中显示给我这个消息:
E/FileByte: 43
我如何获取文件的前16个字符?
英文:
In my application i want read first 16 character of file!<br>
I write below codes but for this byte[ ]
just show me 43!<br>
I want show me first 16 character of bytes.<br>
My codes :
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();
}
Show me this message in logcat
:
E/FileByte: 43
How can i get fisrt 16 character of file?
答案1
得分: 2
要从前16个字节创建一个字符串,可以使用以下代码替代`"+fileBye[16]`:
Log.e("FileByte", new String(fileBye, 0, 16));
请注意,这会根据默认字符编码(在Android上为UTF-8)将前16个**字节**转换为字符串。如果文件中的文本包含非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);
}
英文:
To create a String from the first 16 bytes, use this instead of "+fileBye[16]
:
Log.e("FileByte", new String(fileBye, 0, 16));
Note that this converts the first 16 bytes into a string according to the default character encoding, which is UTF-8 on Android. If the text in the file contains non-ASCII characters, 16 bytes will not be converted to 16 characters.
To extract the first 16 bytes as a byte array, you can use:
byte[] first16 = Arrays.copyOfRange(fileBye, 0, 16);
Or you can read only the first 16 bytes, instead of the entire file:
byte[] first16 = new byte[16];
try (FileInputStream in = new FileInputStream(inputFile)) {
in.read(first16);
}
答案2
得分: 0
在您的情况下,大小为16。
英文:
define a size to your array like this byte[] bytes = new byte[size];
in your case the size is 16
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论