读取文件到字节数组时的冗余字节
Redundancy bytes when read file to byte array
这是我在 android 应用程序中使用的一些将文件读取为字节数组的方法。
- M1:
private static byte[] readFileAsBytes(String filePath)
throws java.io.IOException{
FileInputStream fisTargetFile = new FileInputStream(new File(filePath));
String targetFileStr = IOUtils.toString(fisTargetFile, "UTF-8");
byte[] inputData = IOUtils.toByteArray(new StringReader(targetFileStr),"UTF-8");
return inputData;
}
- M2
private static byte[] readFileAsBytes(String filePath)
throws java.io.IOException{
File file = new File(filePath);
FileInputStream inputFile = new FileInputStream(file);
byte inputData[] = new byte[(int)file.length()];
inputFile.read(inputData);
inputFile.close();
return inputData;
}
我也在用this中的方法
...
但是,当我调试时,我检测到一些冗余字节,例如:
文件文本:ABCDEF
调试时:
- 在 M1 中:inputData: {-17,-69,-65,65,66,67,68,69,70}
我知道A -> 65, B -> 66,... 但是为什么会出现{-17,-69,-65}
-在M2中:比M1出现了很多冗余。
我已经搜索过了,但没有找到相同的问题。
对我有什么建议。
谢谢!!!
String targetFileStr = IOUtils.toString(fisTargetFile, "UTF-8");
byte[] inputData = IOUtils.toByteArray(new StringReader(targetFileStr),"UTF-8");
不要使用中间 String 或 StringReader 将文件的字节放入字节数组。
例如,您不能将 jpg 文件放入字符串中,因为它不是文本。
像在第二个 readFileAsBytes() 中所做的那样,将字节直接放入字节数组中。那一个应该工作。但是您必须检查 inputFile.read(inputData) 的 return 值;并最终形成一个循环。
前三个字节是物料清单。字节顺序标记。参见:https://en.wikipedia.org/wiki/Byte_order_mark
The UTF-8 representation of the BOM is the byte sequence 0xEF,0xBB,0xBF
这是我在 android 应用程序中使用的一些将文件读取为字节数组的方法。
- M1:
private static byte[] readFileAsBytes(String filePath)
throws java.io.IOException{
FileInputStream fisTargetFile = new FileInputStream(new File(filePath));
String targetFileStr = IOUtils.toString(fisTargetFile, "UTF-8");
byte[] inputData = IOUtils.toByteArray(new StringReader(targetFileStr),"UTF-8");
return inputData;
}
- M2
private static byte[] readFileAsBytes(String filePath)
throws java.io.IOException{
File file = new File(filePath);
FileInputStream inputFile = new FileInputStream(file);
byte inputData[] = new byte[(int)file.length()];
inputFile.read(inputData);
inputFile.close();
return inputData;
}
我也在用this中的方法 ...
但是,当我调试时,我检测到一些冗余字节,例如:
文件文本:ABCDEF
调试时:
- 在 M1 中:inputData: {-17,-69,-65,65,66,67,68,69,70}
我知道A -> 65, B -> 66,... 但是为什么会出现{-17,-69,-65}
-在M2中:比M1出现了很多冗余。
我已经搜索过了,但没有找到相同的问题。
对我有什么建议。
谢谢!!!
String targetFileStr = IOUtils.toString(fisTargetFile, "UTF-8");
byte[] inputData = IOUtils.toByteArray(new StringReader(targetFileStr),"UTF-8");
不要使用中间 String 或 StringReader 将文件的字节放入字节数组。
例如,您不能将 jpg 文件放入字符串中,因为它不是文本。
像在第二个 readFileAsBytes() 中所做的那样,将字节直接放入字节数组中。那一个应该工作。但是您必须检查 inputFile.read(inputData) 的 return 值;并最终形成一个循环。
前三个字节是物料清单。字节顺序标记。参见:https://en.wikipedia.org/wiki/Byte_order_mark
The UTF-8 representation of the BOM is the byte sequence 0xEF,0xBB,0xBF