Module java.base
Package java.util

Class HexFormat


  • public final class HexFormat
    extends Object
    Converts binary data to and from its hexadecimal (base 16) string representation. It can also generate the classic Unix hexdump(1) format.

    Example usages:

       // Initialize a 16-byte array from a hexadecimal string
       byte[] bytes = HexFormat.fromString("a1a2a3a4a5a6a7a8a9aaabacadaeaf");
    
       // Display the hexadecimal representation of a file's 256-bit hash code
       MessageDigest sha256 = MessageDigest.getInstance("SHA-256");
       System.out.println(
           HexFormat.toString(sha256.digest(Files.readAllBytes(Paths.get("mydata")))));
    
       // Write the printable representation of a file to the standard output stream
       // in 64-byte chunks formatted according to the supplied Formatter function
       try (InputStream is = Files.newInputStream(Paths.get("mydata"))) {
           HexFormat.dumpAsStream(is, 64,
               (offset, chunk, fromIndex, toIndex) ->
                   String.format("%d %s",
                       offset / 64 + 1,
                       HexFormat.toPrintableString(chunk, fromIndex, toIndex)))
               .forEachOrdered(System.out::println);
       } catch (IOException ioe) {
           ...
       }
    
       // Write the standard input stream to the standard output stream in hexdump format
       HexFormat.dump(System.in, System.out);
     
    Since:
    12
    • Nested Class Summary

      Nested Classes 
      Modifier and Type Class Description
      static interface  HexFormat.Formatter
      Represents a function that formats a byte array as a hexadecimal string.
    • Method Summary

      All Methods Static Methods Concrete Methods 
      Modifier and Type Method Description
      static void dump​(byte[] bytes, int fromIndex, int toIndex, PrintStream out)
      Generates a hexadecimal dump of the contents of a range within the provided byte array and writes it to the provided output stream.
      static void dump​(byte[] bytes, PrintStream out)
      Generates a hexadecimal dump of the contents of the provided byte array and writes it to the provided output stream.
      static void dump​(InputStream in, PrintStream out)
      Generates a hexadecimal dump of the contents of the provided input stream and writes it to the provided output stream.
      static Stream<String> dumpAsStream​(byte[] bytes)
      Generates a dump of the contents of the provided byte array, as a stream of hexadecimal strings in hexdump format.
      static Stream<String> dumpAsStream​(byte[] bytes, int fromIndex, int toIndex, int chunkSize, HexFormat.Formatter formatter)
      Generates a dump of the contents of a range within the provided byte array, as a stream of formatted hexadecimal strings.
      static Stream<String> dumpAsStream​(InputStream in)
      Generates a dump of the contents of the provided input stream, as a stream of hexadecimal strings in hexdump format.
      static Stream<String> dumpAsStream​(InputStream in, int chunkSize, HexFormat.Formatter formatter)
      Generates a dump of the contents of the provided input stream, as a stream of formatted hexadecimal strings.
      static Stream<String> dumpAsStream​(ByteBuffer buffer, int chunkSize, HexFormat.Formatter formatter)
      Generates a dump of the contents of the provided ByteBuffer, as a stream of formatted hexadecimal strings.
      static byte[] fromString​(CharSequence hexString)
      Returns a byte array containing the provided sequence of hexadecimal digits.
      static byte[] fromString​(CharSequence hexString, int fromIndex, int toIndex)
      Returns a byte array containing a range within the provided sequence of hexadecimal digits.
      static String toFormattedString​(byte[] bytes)
      Returns a formatted hexadecimal string representation of the contents of the provided byte array.
      static String toFormattedString​(byte[] bytes, int fromIndex, int toIndex)
      Returns a formatted hexadecimal string representation of the contents of a range within the provided byte array.
      static String toPrintableString​(byte[] bytes)
      Returns a printable representation of the contents of the provided byte array.
      static String toPrintableString​(byte[] bytes, int fromIndex, int toIndex)
      Returns a printable representation of the contents of a range within the provided byte array.
      static String toString​(byte[] bytes)
      Returns a hexadecimal string representation of the contents of the provided byte array, with no additional formatting.
      static String toString​(byte[] bytes, int fromIndex, int toIndex)
      Returns a hexadecimal string representation of a range within the provided byte array, with no additional formatting.
    • Field Detail

      • HEXDUMP_FORMATTER

        public static final HexFormat.Formatter HEXDUMP_FORMATTER
        A formatter that generates the classic Unix hexdump(1) format. It behaves as if:
        
             String.format("%08x  %s  |%s|",
                 offset,
                 HexFormat.toFormattedString(chunk, from, to),
                 HexFormat.toPrintableString(chunk, from, to));
         
    • Method Detail

      • toString

        public static String toString​(byte[] bytes)
        Returns a hexadecimal string representation of the contents of the provided byte array, with no additional formatting.

        The binary value is converted to a string comprising pairs of hexadecimal digits that use only the following ASCII characters:

        0123456789abcdef
        Parameters:
        bytes - a byte array
        Returns:
        a hexadecimal string representation of the byte array. The string length is twice the array length.
        Throws:
        NullPointerException - if bytes is null
      • toString

        public static String toString​(byte[] bytes,
                                      int fromIndex,
                                      int toIndex)
        Returns a hexadecimal string representation of a range within the provided byte array, with no additional formatting.

        The binary value is converted to a string comprising pairs of hexadecimal digits that use only the following ASCII characters:

        0123456789abcdef
        The range to be converted extends from index fromIndex, inclusive, to index toIndex, exclusive. If fromIndex==toIndex, the range to be converted is empty.
        Parameters:
        bytes - a byte array
        fromIndex - the index of the first byte (inclusive) to be converted
        toIndex - the index of the last byte (exclusive) to be converted
        Returns:
        a hexadecimal string representation of the byte array. The string length is twice the number of bytes converted.
        Throws:
        NullPointerException - if bytes is null
        IllegalArgumentException - if fromIndex > toIndex
        ArrayIndexOutOfBoundsException - if fromIndex < 0 or toIndex > bytes.length
      • toFormattedString

        public static String toFormattedString​(byte[] bytes)
        Returns a formatted hexadecimal string representation of the contents of the provided byte array.

        The binary value is converted to a string in the canonical hexdump format of two columns of eight space-separated pairs of hexadecimal digits that use only the following ASCII characters:

        0123456789abcdef

        If the number of bytes to be converted is greater than 16 then System.lineSeparator() characters are inserted after each 16-byte chunk. If the final chunk is less than 16 bytes then the result is padded with spaces to match the length of the preceding chunks. The general output format is as follows:

         00 11 22 33 44 55 66 77  88 99 aa bb cc dd ee ff
         
        Parameters:
        bytes - a byte array
        Returns:
        a formatted hexadecimal string representation of the byte array
        Throws:
        NullPointerException - if bytes is null
      • toFormattedString

        public static String toFormattedString​(byte[] bytes,
                                               int fromIndex,
                                               int toIndex)
        Returns a formatted hexadecimal string representation of the contents of a range within the provided byte array.

        The binary value is converted to a string in the canonical hexdump format of two columns of eight space-separated pairs of hexadecimal digits that use only the following ASCII characters:

        0123456789abcdef

        The range to be converted extends from index fromIndex, inclusive, to index toIndex, exclusive. If fromIndex==toIndex, the range to be converted is empty.

        If the number of bytes to be converted is greater than 16 then System.lineSeparator() characters are inserted after each 16-byte chunk. If the final chunk is less than 16 bytes then the result is padded with spaces to match the length of the preceding chunks. The general output format is as follows:

         00 11 22 33 44 55 66 77  88 99 aa bb cc dd ee ff
         
        Parameters:
        bytes - a byte array
        fromIndex - the index of the first byte (inclusive) to be converted
        toIndex - the index of the last byte (exclusive) to be converted
        Returns:
        a formatted hexadecimal string representation of the byte array
        Throws:
        NullPointerException - if bytes is null
        IllegalArgumentException - if fromIndex > toIndex
        ArrayIndexOutOfBoundsException - if fromIndex < 0 or toIndex > bytes.length
      • toPrintableString

        public static String toPrintableString​(byte[] bytes)
        Returns a printable representation of the contents of the provided byte array.

        The binary value is converted to a string comprising printable StandardCharsets.ISO_8859_1 characters, or '.' if the byte maps to a non-printable character. A non-printable character is one outside of the range '\u0020' through '\u007E' and '\u00A0' through '\u00FF'.

        Parameters:
        bytes - a byte array
        Returns:
        a printable representation of the byte array
        Throws:
        NullPointerException - if bytes is null
      • toPrintableString

        public static String toPrintableString​(byte[] bytes,
                                               int fromIndex,
                                               int toIndex)
        Returns a printable representation of the contents of a range within the provided byte array.

        The binary value is converted to a string comprising printable StandardCharsets.ISO_8859_1 characters, or '.' if the byte maps to a non-printable character. A non-printable character is one outside of the range '\u0020' through '\u007E' and '\u00A0' through '\u00FF'.

        Parameters:
        bytes - a byte array
        fromIndex - the index of the first byte (inclusive) to be converted
        toIndex - the index of the last byte (exclusive) to be converted
        Returns:
        a printable representation of the byte array
        Throws:
        NullPointerException - if bytes is null
        IllegalArgumentException - if fromIndex > toIndex
        ArrayIndexOutOfBoundsException - if fromIndex < 0 or toIndex > bytes.length
      • fromString

        public static byte[] fromString​(CharSequence hexString)
        Returns a byte array containing the provided sequence of hexadecimal digits. The sequence may be prefixed with the hexadecimal indicator "0x". The optional prefix of "0x" is ignored.

        The binary value is generated from pairs of hexadecimal digits that use only the following ASCII characters:

        0123456789abcdefABCDEF
        Parameters:
        hexString - an even numbered sequence of hexadecimal digits. If this is a CharBuffer then its position does not get advanced.
        Returns:
        a byte array
        Throws:
        IllegalArgumentException - if hexString has an odd number of digits or contains an illegal hexadecimal character
        NullPointerException - if hexString is null
      • fromString

        public static byte[] fromString​(CharSequence hexString,
                                        int fromIndex,
                                        int toIndex)
        Returns a byte array containing a range within the provided sequence of hexadecimal digits. The sequence may be prefixed with the hexadecimal indicator "0x". The optional prefix of "0x" is ignored.

        The binary value is generated from pairs of hexadecimal digits that use only the following ASCII characters:

        0123456789abcdefABCDEF
        Parameters:
        hexString - an even numbered sequence of hexadecimal digits. If this is a CharBuffer then its position does not get advanced.
        fromIndex - the index of the first digit (inclusive) to be converted
        toIndex - the index of the last digit (exclusive) to be converted
        Returns:
        a byte array
        Throws:
        IllegalArgumentException - if hexString has an odd number of digits or contains an illegal hexadecimal character, or if fromIndex > toIndex
        NullPointerException - if hexString is null
        ArrayIndexOutOfBoundsException - if fromIndex < 0 or toIndex > hexString.length()
      • dumpAsStream

        public static Stream<String> dumpAsStream​(InputStream in)
        Generates a dump of the contents of the provided input stream, as a stream of hexadecimal strings in hexdump format. This method outputs the same format as dump(byte[],PrintStream), without the System.lineSeparator() characters.

        If the input is not a multiple of 16 bytes then the final chunk will be shorter than the preceding chunks. The result will be padded with spaces to match the length of the preceding chunks.

        On return, the generated stream lazily consumes the input stream. This method does not close the input stream and may block indefinitely reading from it. The behavior for the case where it is asynchronously closed, or the thread interrupted, is highly input stream specific, and therefore not specified.

        If an I/O error occurs reading from the input stream then it may not be at end-of-stream and may be in an inconsistent state. It is strongly recommended that the input stream be promptly closed if an I/O error occurs.

        Parameters:
        in - the input stream, non-null
        Returns:
        a new infinite sequential ordered stream of hexadecimal strings
        Throws:
        NullPointerException - if in is null
      • dumpAsStream

        public static Stream<String> dumpAsStream​(InputStream in,
                                                  int chunkSize,
                                                  HexFormat.Formatter formatter)
        Generates a dump of the contents of the provided input stream, as a stream of formatted hexadecimal strings. Each string is formatted according to the formatter function, if not null. Otherwise, this method outputs the same format as dump(byte[],PrintStream), without the System.lineSeparator() characters.

        On return, the generated stream lazily consumes the input stream. This method does not close the input stream and may block indefinitely reading from it. The behavior for the case where it is asynchronously closed, or the thread interrupted, is highly input stream specific, and therefore not specified.

        If an I/O error occurs reading from the input stream then it may not be at end-of-stream and may be in an inconsistent state. It is strongly recommended that the input stream be promptly closed if an I/O error occurs.

        If an error occurs in the formatter then an unchecked exception will be thrown from the underlying Stream method.

        Parameters:
        in - the input stream, non-null
        chunkSize - the number of bytes-per-chunk (typically 16)
        formatter - a hexdump formatting function, or null
        Returns:
        a new infinite sequential ordered stream of hexadecimal strings
        Throws:
        IllegalArgumentException - if chunkSize <= 0
        NullPointerException - if in is null
      • dumpAsStream

        public static Stream<String> dumpAsStream​(byte[] bytes)
        Generates a dump of the contents of the provided byte array, as a stream of hexadecimal strings in hexdump format. This method outputs the same format as dump(byte[],PrintStream), without the System.lineSeparator() characters.

        If the input is not a multiple of 16 bytes then the final chunk will be shorter than the preceding chunks. The result will be padded with spaces to match the length of the preceding chunks.

        Parameters:
        bytes - a byte array, assumed to be unmodified during use
        Returns:
        a new sequential ordered stream of hexadecimal strings
        Throws:
        NullPointerException - if bytes is null
      • dumpAsStream

        public static Stream<String> dumpAsStream​(byte[] bytes,
                                                  int fromIndex,
                                                  int toIndex,
                                                  int chunkSize,
                                                  HexFormat.Formatter formatter)
        Generates a dump of the contents of a range within the provided byte array, as a stream of formatted hexadecimal strings. Each string is formatted according to the formatter function, if not null. Otherwise, this method outputs the same format as dump(byte[],PrintStream), without the System.lineSeparator() characters.

        The range to be converted extends from index fromIndex, inclusive, to index toIndex, exclusive. If fromIndex==toIndex, the range to be converted is empty. If the input is not a multiple of chunkSize then the final chunk will be shorter than the preceding chunks. The result may be padded with spaces to match the length of the preceding chunks.

        If an error occurs in the formatter then an unchecked exception will be thrown from the underlying Stream method.

        Parameters:
        bytes - a byte array, assumed to be unmodified during use
        fromIndex - the index of the first byte (inclusive) to be converted
        toIndex - the index of the last byte (exclusive) to be converted
        chunkSize - the number of bytes-per-chunk (typically 16)
        formatter - a hexdump formatting function, or null
        Returns:
        a new sequential ordered stream of hexadecimal strings
        Throws:
        NullPointerException - if bytes is null
        IllegalArgumentException - if fromIndex > toIndex or chunkSize <= 0
        ArrayIndexOutOfBoundsException - if fromIndex < 0 or toIndex > bytes.length
      • dumpAsStream

        public static Stream<String> dumpAsStream​(ByteBuffer buffer,
                                                  int chunkSize,
                                                  HexFormat.Formatter formatter)
        Generates a dump of the contents of the provided ByteBuffer, as a stream of formatted hexadecimal strings. Each string is formatted according to the formatter function, if not null. Otherwise, this method outputs the same format as dump(byte[],PrintStream), without the System.lineSeparator() characters.

        If the input is not a multiple of chunkSize then the final chunk will be shorter than the preceding chunks. The result may be padded with spaces to match the length of the preceding chunks.

        Access to the ByteBuffer is relative and its position gets advanced to the buffer's limit.

        If an error occurs in the formatter then an unchecked exception will be thrown from the underlying Stream method.

        Parameters:
        buffer - a byte buffer, assumed to be unmodified during use
        chunkSize - the number of bytes-per-chunk (typically 16)
        formatter - a hexdump formatting function, or null
        Returns:
        a new sequential ordered stream of hexadecimal strings
        Throws:
        IllegalArgumentException - if chunkSize <= 0
        NullPointerException - if buffer is null
      • dump

        public static void dump​(byte[] bytes,
                                PrintStream out)
                         throws IOException
        Generates a hexadecimal dump of the contents of the provided byte array and writes it to the provided output stream. This method behaves as if:
        
             byte[] bytes = ...
             PrintStream out = ...
             HexFormat.dumpAsStream(bytes, 16,
                 (offset, chunk, from, to) ->
                     String.format("%08x  %s  |%s|",
                         offset,
                         HexFormat.toFormattedString(chunk, from, to),
                         HexFormat.toPrintableString(chunk, from, to)))
                 .forEachOrdered(out::println);
         

        This method does not close the output stream and may block indefinitely writing to it. The behavior for the case where it is asynchronously closed, or the thread interrupted, is highly output stream specific, and therefore not specified.

        If an I/O error occurs writing to the output stream, then it may be in an inconsistent state. It is strongly recommended that the output stream be promptly closed if an I/O error occurs.

        Parameters:
        bytes - the byte array, assumed to be unmodified during use
        out - the output stream, non-null
        Throws:
        IOException - if an I/O error occurs when writing
        NullPointerException - if bytes or out is null
      • dump

        public static void dump​(byte[] bytes,
                                int fromIndex,
                                int toIndex,
                                PrintStream out)
                         throws IOException
        Generates a hexadecimal dump of the contents of a range within the provided byte array and writes it to the provided output stream. This method outputs the same format as dump(byte[],PrintStream).

        The range to be converted extends from index fromIndex, inclusive, to index toIndex, exclusive. If fromIndex==toIndex, the range to be converted is empty.

        This method does not close the output stream and may block indefinitely writing to it. The behavior for the case where it is asynchronously closed, or the thread interrupted, is highly output stream specific, and therefore not specified.

        If an I/O error occurs writing to the output stream, then it may be in an inconsistent state. It is strongly recommended that the output stream be promptly closed if an I/O error occurs.

        Parameters:
        bytes - the byte array, assumed to be unmodified during use
        fromIndex - the index of the first byte (inclusive) to be converted
        toIndex - the index of the last byte (exclusive) to be converted
        out - the output stream, non-null
        Throws:
        IOException - if an I/O error occurs when writing
        NullPointerException - if bytes or out is null
        IllegalArgumentException - if fromIndex > toIndex
        ArrayIndexOutOfBoundsException - if fromIndex < 0 or toIndex > bytes.length
      • dump

        public static void dump​(InputStream in,
                                PrintStream out)
                         throws IOException
        Generates a hexadecimal dump of the contents of the provided input stream and writes it to the provided output stream. This method outputs the same format as dump(byte[],PrintStream).

        Reads all bytes from the input stream. On return, the input stream will be at end-of-stream. This method does not close either stream and may block indefinitely reading from the input stream, or writing to the output stream. The behavior for the case where the input and/or output stream is asynchronously closed, or the thread interrupted, is highly input stream and output stream specific, and therefore not specified.

        If an I/O error occurs reading from the input stream or writing to the output stream, then it may do so after some bytes have been read or written. Consequently the input stream may not be at end-of-stream and one, or both, streams may be in an inconsistent state. It is strongly recommended that both streams be promptly closed if an I/O error occurs.

        Parameters:
        in - the input stream, non-null
        out - the output stream, non-null
        Throws:
        IOException - if an I/O error occurs when reading or writing
        NullPointerException - if in or out is null