checkpoint
[slipway.git] / src / org / ibex / util / ProgressOutputStream.java
1 package org.ibex.util;
2 import java.io.*;
3
4 public class ProgressOutputStream extends FilterOutputStream {
5
6     private int size = -1;
7     private int bytes = 0;
8     private String title;
9
10     public ProgressOutputStream(String title, OutputStream o) { this(title, o, -1); }
11
12     public ProgressOutputStream(String title, OutputStream o, int size) {
13         super(o);
14         this.size = size;
15         this.title = title;
16     }
17
18     public void write(int i) throws IOException {
19         super.write(i);
20         bytes++;
21         update();
22     }
23
24     public void write(byte[] b, int off, int len) throws IOException {
25         super.write(b, off, len);
26         bytes += len;
27         update();
28     }
29
30     private void update() {
31         System.out.print("\r                                                              \r");
32         System.out.print(title);
33         if (size != -1) {
34             int frac = (100 * bytes) / size;
35             String fracs = frac+"";
36             while(fracs.length()<3) fracs = " "+fracs;
37             System.out.print(" ");
38             System.out.print("\033[32m");
39             System.out.print(fracs+"%");
40             System.out.print("\033[0m");
41         }
42         System.out.print(" ");
43         System.out.print(bytes);
44         System.out.print(" bytes ");
45     }
46
47     public void close() throws IOException {
48         super.close();
49         bytes = size;
50         update();
51         System.out.println();
52     }
53 }