0

I am trying to read a hexadecimal file from java code. All I want is pick the hex values and save it in a String (or any other format) , without convert them. I've already tried with a BufferedReader, and saving the values in a StringBuilder, but I don't know why the values are automatically converted in decimal values when I use StringBuilder.toString() method.

Any suggestion ?

Roman Panaget
  • 1,578
  • 12
  • 21
  • Can you post a reproducible example? – August Nov 27 '14 at 19:29
  • There is no such thing as a hex file. There are binary files and text files. Hex is a representation, not a datatype. If you want hex in your String you will have to convert it. – user207421 Nov 27 '14 at 19:33

1 Answers1

0

You can use java.util.Formatter. Try this:

StringBuilder _stringBuilder = new StringBuilder();
for (byte _byte : byteArray) 
{
        _stringBuilder.append(String.format("%02X ", _byte));
}

More info here.

Community
  • 1
  • 1
  • Must it too obligatory here. –  Nov 27 '14 at 19:44
  • Why do you mention a class that isn't used in your example code? – user207421 Nov 27 '14 at 20:03
  • I mean formatting rules: http://docs.oracle.com/javase/6/docs/api/java/util/Formatter.html#syntax – Yegor Korotetskiy Nov 27 '14 at 20:05
  • That looks pretty good but I have a file, not a byte array, any suggestion? – Roman Panaget Nov 27 '14 at 20:38
  • Just use the getResourceAsStream(fileName) function, for example, to load your file to the InputStream. And then perform formatting routine. – Yegor Korotetskiy Nov 27 '14 at 20:51
  • `String.format` will make a new Formatter for each and every iterated byte. A better alternative is to replace the StringBuilder with `Formatter formatter = new Formatter();` (which will create and wrap a StringBuilder internally) and replace the statement inside the loop with `formatter.format("%02X ", _byte);`. The final result can be achieved with `formatter.toString()`. – VGR Nov 29 '14 at 17:19