public static final char[] HEX = "0123456789ABCDEF".toCharArray();
public static String bytesToHex(byte[] bytes, int length) {
char[] hexChars = new char[bytes.length * 2];
for (int j = 0; j < Math.min(length, bytes.length); j++) {
int v = bytes[j] & 0xFF;
hexChars[j * 2] = HEX[v >>> 4];
hexChars[j * 2 + 1] = HEX[v & 0x0F];
}
return new String(hexChars);
}
public static byte[] hex2Byte(String hex) {
String[] parts = hex.split(" ");
byte[] bytes = new byte[parts.length];
for (int i = 0; i < parts.length; i++) {
bytes[i] = (byte) Integer.parseInt(parts[i], 16);
}
return bytes;
}
public static String randomHexString(int length) {
StringBuffer result = new StringBuffer();
Random random = new Random();
try {
for (int i = 0; i < length; i++) {
String hexString = Integer.toHexString(random.nextInt(255));
if (hexString.length() == 1) {
result.append("0");
}
result.append(hexString).append(" ");
}
return result.toString();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public static byte[] insertTail(byte[] arr, byte value) {
if (arr == null) {
return null;
}
arr = Arrays.copyOf(arr, arr.length + 1);
arr[arr.length - 1] = value;
return arr;
}
private static String read(File file) {
if (file == null || !file.exists()) {
return null;
}
StringBuilder builder = new StringBuilder();
Scanner scanner;
try {
scanner = new Scanner(file);
while (scanner.hasNextLine()) {
builder.append(scanner.nextLine()).append('\n');
}
builder.deleteCharAt(builder.length() - 1);
} catch (FileNotFoundException e) {
return null;
}
if (scanner != null) {
scanner.close();
}
return builder.toString();
}
public static void write(File file, String content) {
if (file == null) {
return;
}
FileWriter writer;
try {
writer = new FileWriter(file);
writer.write(content);
writer.flush();
} catch (IOException e) {
return;
}
if (writer != null) {
try {
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
因篇幅问题不能全部显示,请点此查看更多更全内容