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