# 1 楼答案 快速帮助看起来像这样 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(); } 为了简单起见,我跳过了几个边缘案例。但我认为这是一个好的开始。实际上,您必须检查角色是否可转换为十六进制,并处理所有可能引发的异常 主要方法如下所示 public static void main(String[] args) throws IOException { File file = new File("sample.pdf"); String hex = toHex(file); System.out.println(hex); }
# 2 楼答案 一个很好的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)); } 这假设文件不是很大。(但在这种情况下,十六进制是没有意义的。)
# 1 楼答案
快速帮助看起来像这样
为了简单起见,我跳过了几个边缘案例。但我认为这是一个好的开始。实际上,您必须检查角色是否可转换为十六进制,并处理所有可能引发的异常
主要方法如下所示
# 2 楼答案
一个很好的
ByteBuffer
用例(尽管byte[]
在这里就足够了):速度提升:
这假设文件不是很大。(但在这种情况下,十六进制是没有意义的。)