如果我有一个包含我想要的确切 byte[]
数据的文件:
[-119, 45, 67, ...]
如何将这些值读入byte
数组?我是否必须将它们作为 String
读取,然后将这些 String
值转换为 byte
值?
这就是我目前正在做的,它有效,但速度很慢:
BufferedReader reader = null;
String mLine = null;
AssetManager assetManager = CustomApplication.getCustomAppContext().getAssets();
try {
reader = new BufferedReader(new InputStreamReader(assetManager.open(fileName)));
mLine = reader.readLine();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
String[] byteValues = mLine.substring(1, mLine.length() - 1).split(",");
byte[] imageBytes = new byte[byteValues.length];
for (int i = 0; i < imageBytes.length; i++) {
imageBytes[i] = Byte.valueOf(byteValues[i].trim());
}
return imageBytes;
更新:似乎对我想要完成的事情有误解。我的文件在我的最终字节数组中包含我想要的精确字节数据。例如,我想用 exactly 转换一个文件
[-119, 45, 67, ...]
进入 byte[]
调用结果
result[0] = -119
result[1] = 45
result[2] = 67
最佳答案
BufferedReader
用于读取char
单元。使用读取 byte
单元的 BufferedInputStream
并使用 ByteArrayOutputStream
帮助您填充字节数组:
BufferedInputStream bis = new BufferedInputStream(assetManager.open(fileName));
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
int theByte;
while((theByte = bis.read()) != -1)
{
buffer.write(theByte);
}
bis.close();
buffer.close();
byte[] result = buffer.toByteArray();
关于java - 将文件中包含的字节值读入字节数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24439961/