2 回答

TA貢獻1820條經(jīng)驗 獲得超2個贊
快速幫助看起來像這樣
static String toHex(File file) throws IOException {
InputStream is = new BufferedInputStream(new FileInputStream(file));
int value = 0;
StringBuilder hex = new StringBuilder();
while ((value = inputStream.read()) != -1) {
hex.append(String.format("%02X ", value));
}
return hex.toString();
}
為了簡單起見,我跳過了一些邊緣情況。但我認為這是一個好的開始。實際上,您必須檢查字符是否可轉(zhuǎn)換為十六進制并處理所有可能引發(fā)的異常。
main 方法看起來像這樣。
public static void main(String[] args) throws IOException {
File file = new File("sample.pdf");
String hex = toHex(file);
System.out.println(hex);
}

TA貢獻1875條經(jīng)驗 獲得超3個贊
一個很好的用例ByteBuffer(盡管byte[]在這里就足夠了):
byte[] toHex(Path path) {
byte[] content = Files.readAllBytes(path);
ByteBuffer buf = ByteBuffer.allocate(content.length * 2);
for (byte b : content) {
byte[] cc = String.format("%02x", 0xFF & b).getBytes(StandardCharsets.US_ASCII);
buf.put(cc);
}
return buf.array();
}
速度提升:
for (byte b : content) {
int c = (b >> 4) & 0xF;
int d = b & 0xF;
buf.put((byte) (c < 10 ? '0' + c : 'a' + c - 10));
buf.put((byte) (d < 10 ? '0' + d : 'a' + d - 10));
}
這假設文件不大。(但在這種情況下,十六進制就沒有意義。)
添加回答
舉報