Java: A Language for the Internet

[top]

  1. Static object language but dynamic loading
  2. Example: Hexdump of a file

    /*
     *   File hex dump written in Java
     *
     *   java Hexdump [file ...]
     */
    import    java.io.*;
    
    class Hexdump {
      static void putXDigit(int d) {
        System.out.print(Character.forDigit(d & 0x0f, 16));
      }
    
      static void putHex(int c) {
        putXDigit(c >>> 4);
        putXDigit(c);
      }
    
      static void putChar(int n) {
        char c = (char)n;
        if (c > 0x7f || Character.isISOControl(c))
          System.out.print(".");
        else
          System.out.print(c);
      }
    
      static void doDump(InputStream in) {
        final int BYTES = 16;
        byte[] buff = new byte[BYTES];
        int n;
        try {
          while ((n = in.read(buff)) > 0) {
            for (int i = 0; i < BYTES; ++i) {
              if (i < n)
                putHex(buff[i] & 0xff);
              else
                System.out.print("  ");
              System.out.print(" ");
              if ((i + 1) % (BYTES / 2) == 0)
                System.out.print(" ");
            }
            System.out.print("|");
            for (int i = 0; i < n; ++i)
              putChar(buff[i] & 0xff);
            System.out.println("|");
          }
        } catch (IOException e) {
          System.err.println("IO error: " + e.toString());
          System.exit(1);
        }
      }
    
      static InputStream nextFile(String fname) {
        FileInputStream ifs = null;
        try {
          ifs = new FileInputStream(fname);
        } catch (FileNotFoundException e) {
          System.err.println("Cannot open " + fname);
        }
        return (InputStream)ifs;
      }
    
      public static void main(String args[]) {
        if (args.length == 0)
          doDump(System.in);
        for (int i = 0; i < args.length; ++i) {
          InputStream is = nextFile(args[i]);
          doDump(is);
          try { is.close(); } catch (IOException e) { };
        }
      }
    }
    

[top]