Java:文件到十六进制

前端之家收集整理的这篇文章主要介绍了Java:文件到十六进制前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有一个 Java文件
  1. FileInputStream in = null;
  2. try{
  3. in = new FileInputStream("C:\\pic.bmp");
  4. }catch{}

我想将pic.bmp转换为十六进制数值的数组,因此我可以将其编辑并保存为修改版本.

有没有一个java类来做这个?

解决方法

你运气好几个月前我不得不这样做.这是一个从压缩版本,从命令行接受两个参数.两个comand行参数都是文件名…第一个是输入文件,第二个是输出文件.输入文件以二进制读取,输出文件写为ASCII十六进制.希望你能适应你的需要.
  1. import java.io.BufferedWriter;
  2. import java.io.File;
  3. import java.io.FileInputStream;
  4. import java.io.FileWriter;
  5. import java.io.IOException;
  6.  
  7. public class BinToHex
  8. {
  9. private final static String[] hexSymbols = { "0","1","2","3","4","5","6","7","8","9","a","b","c","d","e","f" };
  10.  
  11. public final static int BITS_PER_HEX_DIGIT = 4;
  12.  
  13. public static String toHexFromByte(final byte b)
  14. {
  15. byte leftSymbol = (byte)((b >>> BITS_PER_HEX_DIGIT) & 0x0f);
  16. byte rightSymbol = (byte)(b & 0x0f);
  17.  
  18. return (hexSymbols[leftSymbol] + hexSymbols[rightSymbol]);
  19. }
  20.  
  21. public static String toHexFromBytes(final byte[] bytes)
  22. {
  23. if(bytes == null || bytes.length == 0)
  24. {
  25. return ("");
  26. }
  27.  
  28. // there are 2 hex digits per byte
  29. StringBuilder hexBuffer = new StringBuilder(bytes.length * 2);
  30.  
  31. // for each byte,convert it to hex and append it to the buffer
  32. for(int i = 0; i < bytes.length; i++)
  33. {
  34. hexBuffer.append(toHexFromByte(bytes[i]));
  35. }
  36.  
  37. return (hexBuffer.toString());
  38. }
  39.  
  40. public static void main(final String[] args) throws IOException
  41. {
  42. try
  43. {
  44. FileInputStream fis = new FileInputStream(new File(args[0]));
  45. BufferedWriter fos = new BufferedWriter(new FileWriter(new File(args[1])));
  46.  
  47. byte[] bytes = new byte[800];
  48. int value = 0;
  49. do
  50. {
  51. value = fis.read(bytes);
  52. fos.write(toHexFromBytes(bytes));
  53.  
  54. }while(value != -1);
  55.  
  56. fos.flush();
  57. fos.close();
  58. }
  59. catch(Exception e)
  60. {
  61. e.printStackTrace();
  62. }
  63. }
  64. }

猜你在找的Java相关文章