Java Hex Dump hexDump(InputStream is, PrintStream ps, int maxRead, int bytesPerLine)

Here you can find the source of hexDump(InputStream is, PrintStream ps, int maxRead, int bytesPerLine)

Description

hex Dump

License

Apache License

Declaration

public static int hexDump(InputStream is, PrintStream ps, int maxRead, int bytesPerLine) 

Method Source Code


//package com.java2s;
//License from project: Apache License 

import java.io.IOException;
import java.io.InputStream;
import java.io.PrintStream;
import java.util.Arrays;

public class Main {
    final static char[] HEXTAB = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };

    public static int hexDump(InputStream is, PrintStream ps, int maxRead, int bytesPerLine) {
        int read, chr, i, result;
        char[] pad;
        StringBuffer left, right;

        if (1 > bytesPerLine) {
            bytesPerLine = 1;//from   w  w w  .java  2s  . co  m
        }

        left = new StringBuffer();
        right = new StringBuffer();

        result = 0;

        for (read = 0, i = 0;;) {
            if (-1 != maxRead) {
                if (maxRead <= read) {
                    break;
                }
            }

            try {
                if (-1 == (chr = is.read())) {
                    break;
                }
            } catch (IOException ioe) {
                break;
            }

            result++;

            if (0 < i++) {
                left.append(' ');
            }

            left.append(HEXTAB[chr >>> 4]);
            left.append(HEXTAB[chr & 0x0f]);

            right.append((chr < ' ') ? '.' : (char) chr);

            if (0 == (i % bytesPerLine)) {
                ps.print(left.toString());
                ps.print("    ");
                ps.println(right.toString());

                left.setLength(0);
                right.setLength(0);

                i = 0;
            }
        }

        if (0 < i) {
            pad = new char[((bytesPerLine - i) * 3) + 4];
            Arrays.fill(pad, ' ');

            ps.print(left.toString());
            ps.print(pad);
            ps.println(right.toString());
        }

        return result;
    }
}

Related

  1. hexdump(byte[] bytes, OutputStream out)
  2. hexDump(byte[] data)
  3. hexDump(InputStream is, OutputStream os)
  4. hexDump(PrintStream out, String s, byte b[], int n)
  5. hexDump(String prompt, byte[] bs)
  6. hexDumpBytes(PrintStream out, long offset, byte[] bytes)