获取Android中文件的字节如何?

huangapple go评论51阅读模式
英文:

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) + &quot;/&quot; + &quot;girnmqlyv0.pdf&quot;;
File file = new File(inputFile);
                try {
                    byte[] fileBye = FileUtils.readFileToByteArray(file);
                    Log.e(&quot;FileByte&quot;, &quot;&quot;+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个字节创建一个字符串,可以使用以下代码替代`&quot;+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 &quot;+fileBye[16]:

Log.e(&quot;FileByte&quot;, 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

huangapple
  • 本文由 发表于 2020年8月1日 19:05:47
  • 转载请务必保留本文链接:https://go.coder-hub.com/63204493.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定