二进制文件转十六进制字符串
第一版本
public static String binFileToHexStrV1(File file) {
StringBuilder hexStr = new StringBuilder();
try (
DataInputStream bin = new DataInputStream(new FileInputStream(file));
) {
byte temp = 0;
for (int i = 0; i < file.length(); i++) {
temp = bin.readByte();
// 以十六进制的无符号整数形式返回一个字符串表示形式。
String str = Integer.toHexString(temp);
if (str.length() == 8) {
// 去掉补位的f
str = str.substring(6);
}
if (str.length() == 1) {
str = "0" + str;
}
hexStr.append(str.toUpperCase());
}
} catch (Exception e) {
e.printStackTrace();
}
return hexStr.toString();
}
读取100k二进制文件需要5397毫秒
第二版本
public static String binFileToHexStrV2(File file) {
StringBuilder hexStr = new StringBuilder();
try (
DataInputStream bin = new DataInputStream(new FileInputStream(file));
) {
for (int i = 0; i < file.length(); i++) {
hexStr.append(String.format("%02X", bin.read()));
}
} catch (Exception e) {
e.printStackTrace();
}
return hexStr.toString();
}
读取100k二进制文件需要6832毫秒
第三版本
public static String binFileToHexStrV3(File file) {
StringBuilder hexStr = new StringBuilder();
byte[] data = new byte[1024*5];
try (
DataInputStream bin = new DataInputStream(new FileInputStream(file));
) {
while (true) {
int a = 0;
a = bin.read(data);
if (a == -1) {
break;
}
byte[] data2 = new byte[a];
for (int i = 0; i < a; i++) {
data2[i] = data[i];
}
hexStr.append(DatatypeConverter.printHexBinary(data2));
}
} catch (Exception e) {
e.printStackTrace();
}
return hexStr.toString();
}
读取100k二进制文件需要21毫秒
第四版本
public static String binFileToHexStrV4(File file) {
char[] hexCode = "0123456789ABCDEF".toCharArray();
StringBuilder hexStr = new StringBuilder();
byte[] data = new byte[1024*5];
try (
DataInputStream bin = new DataInputStream(new FileInputStream(file));
) {
while (true) {
int a = 0;
a = bin.read(data);
if (a == -1) {
break;
}
for (int i = 0; i < a; i++) {
hexStr.append(hexCode[(data[i] >> 4) & 0xF]);
hexStr.append(hexCode[(data[i] & 0xF)]);
}
}
} catch (Exception e) {
e.printStackTrace();
}
return hexStr.toString();
}
读取100k二进制文件需要7毫秒
最后终于脱掉了程序慢的帽子。
总结: 读取文件时应适当调整读取的次数以及循环的次数,减少不必要的耗时。