1
2
3
4 package jwutil.io;
5 import java.io.PrintStream;
6 import java.io.FilterOutputStream;
7 import java.io.IOException;
8
9 /***
10 * ANSIColorStream provides ANSI-color streams.
11 *
12 * Comes in handy when outputting to a terminal, simply use
13 * ANSIColorStream.red.println("in red") to print a line in red.
14 *
15 * Set ANSIColorStream.OFF to true to turn this off.
16 *
17 * @see jwutil.io.ANSIColorStream#OFF
18 * @author Godmar Back <gback@cs.utah.edu, @stanford.edu>
19 */
20 public class ANSIColorStream extends PrintStream {
21 public static boolean OFF = false;
22 public static final int RESET = 0;
23 public static final int BRIGHT = 1;
24 public static final int DIM = 2;
25 public static final int UNDERLINE = 3;
26 public static final int BLINK = 4;
27 public static final int REVERSE = 7;
28 public static final int HIDDEN = 8;
29 public static final int BLACK = 0;
30 public static final int RED = 1;
31 public static final int GREEN = 2;
32 public static final int YELLOW = 3;
33 public static final int BLUE = 4;
34 public static final int MAGENTA = 5;
35 public static final int CYAN = 6;
36 public static final int GRAY = 7;
37 public static final int WHITE = 8;
38 public static ANSIColorStream blue = new ANSIColorStream(System.out,
39 ANSIColorStream.BLUE);
40 public static ANSIColorStream red = new ANSIColorStream(System.out,
41 ANSIColorStream.RED);
42 public static ANSIColorStream green = new ANSIColorStream(System.out,
43 ANSIColorStream.GREEN);
44 public static ANSIColorStream cyan = new ANSIColorStream(System.out,
45 ANSIColorStream.CYAN);
46 public ANSIColorStream(final PrintStream out, final int fgColor) {
47 this(out, fgColor, WHITE);
48 }
49 public ANSIColorStream(final PrintStream pout, final int fgColor,
50 final int bgColor) {
51 super(new FilterOutputStream(pout) {
52 private void setColor() {
53 ((PrintStream) out).print("\033[0;" + (30 + fgColor) + ";"
54 + (40 + bgColor) + "m");
55 }
56 private void resetColor() {
57 ((PrintStream) out).print("\033[00m");
58 }
59 public void write(int b) throws IOException {
60 if (OFF) {
61 out.write(b);
62 } else {
63 setColor();
64 out.write(b);
65 resetColor();
66 }
67 }
68 public void write(byte[] b, int off, int len) throws IOException {
69 if (OFF) {
70 out.write(b, off, len);
71 } else {
72 setColor();
73 out.write(b, off, len);
74 resetColor();
75 }
76 }
77 });
78 }
79 public static void main(String av[]) {
80 for (int i = 0; i < 8; i++) {
81 for (int j = 0; j < 9; j++) {
82 PrintStream out = new ANSIColorStream(System.out, i, j);
83 out.print(av.length > 0 ? av[0] : "testing");
84 }
85 System.out.println();
86 }
87 }
88 }