Java读取文件到字节数组:
//读取文件
public static byte[] getArr() throws Exception{
File file = new File("C:\\Users\\SongShilun\\Desktop\\mcu6_Files\\Ztest40.MCU6");
FileInputStream fis = new FileInputStream(file);
long length = file.length();
byte[] buffer = new byte[(int) length];
int offset = 0;
int numRead = 0;
while (offset < buffer.length
&& (numRead = fis.read(buffer, offset, buffer.length - offset)) >= 0) {
offset += numRead;
}
// 确保所有数据均被读取
if (offset != buffer.length) {
throw new IOException("Could not completely read file " + file.getName());
}
fis.close();
return buffer;
}
16进制与字节数组的转化
//字节数组转16进制
public static String byteArrToHex(byte[] btArr) {
char strArr[] = new char[btArr.length * 2];
int i = 0;
for (byte bt : btArr) {
strArr[i++] = HexCharArr[bt>>>4 & 0xf];
strArr[i++] = HexCharArr[bt & 0xf];
}
return new String(strArr);
}
//16进制转字节
public static byte[] hexStringToBytes(String hexString) {
if (hexString == null || hexString.equals("")) {
return null;
}
hexString = hexString.toUpperCase();
int length = hexString.length() / 2;
char[] hexChars = hexString.toCharArray();
byte[] d = new byte[length];
for (int i = 0; i < length; i++) {
int pos = i * 2;
d[i] = (byte) (charToByte(hexChars[pos]) << 4 | charToByte(hexChars[pos + 1]));
}
return d;
}
//单个字符转字节
private static byte charToByte(char c){
String chars = "0123456789ABCDEF";
byte b = (byte)chars.indexOf(c);
return b;
}
每16个字节换行打印
//每32个字节换行打印
public static void formatPrint(String hexStr){
int no = 0;
int length = hexStr.length();
for (int i=0;i<length;i++){
if ((i+1)%32==0){
String s = twoSpaceTwo(hexStr.substring(i - 31, i + 1));
System.out.println("no"+no+":"+s);
no++;
if (length-i<32){
return;
}
}
}
}
字符串每隔两位插入空格
//隔两位打印一个空格----正则表达式方法
public static String twoSpaceTwo(String replace){
String regex = "(.{2})";
replace = replace.replaceAll(regex, "$1 ");
return replace;
}
最后一个参考自:https://blog.csdn.net/qq_40321119/article/details/105217092