changes.
[IRC.git] / Robust / src / ClassLibrary / SSJava / FileInputStream.java
1 public class FileInputStream extends InputStream {
2   private int fd;
3
4   public FileInputStream(String pathname) {
5     fd = nativeOpen(pathname.getBytes());
6   }
7
8   public FileInputStream(File path) {
9     fd = nativeOpen(path.getPath().getBytes());
10   }
11
12   public int getfd() {
13     return fd;
14   }
15
16   private static native int nativeOpen(byte[] filename);
17
18   private static native int nativeRead(int fd, byte[] array, int numBytes);
19
20   private static native int nativePeek(int fd);
21
22   private static native void nativeClose(int fd);
23
24   private static native int nativeAvailable(int fd);
25
26   public int read() {
27     byte b[] = new byte[1];
28     int retval = read(b);
29     if (retval == -1 || retval == 0)
30       return -1;
31
32     // if carriage return comes back, dump it
33     if (b[0] == 13) {
34       return read();
35     }
36
37     // otherwise return result
38     return b[0];
39   }
40
41   public int peek() {
42     return nativePeek(fd);
43   }
44
45   public int read(byte[] b, int offset, int len) {
46     if (offset < 0 || len < 0 || offset + len > b.length) {
47       return -1;
48     }
49     byte readbuf[] = new byte[len];
50     int rtr = nativeRead(fd, readbuf, len);
51     for (int i = offset; i < len + offset; i++) {
52       b[i] = readbuf[i - offset];
53     }
54     return rtr;
55   }
56
57   public int read(byte[] b) {
58     return nativeRead(fd, b, b.length);
59   }
60
61   public String readLine() {
62     String line = "";
63     int c = read();
64
65     // if we're already at the end of the file
66     // or there is an error, don't even return
67     // the empty string
68     if (c <= 0) {
69       return null;
70     }
71
72     // ASCII 13 is carriage return, check for that also
73     while (c != '\n' && c != 13 && c > 0) {
74       line += (char) c;
75       c = read();
76     }
77
78     // peek and consume characters that are carriage
79     // returns or line feeds so the whole line is read
80     // and returned, and none of the line-ending chars
81     c = peek();
82     while (c == '\n' || c == 13) {
83       c = read();
84       c = peek();
85     }
86
87     return line;
88   }
89
90   public void close() {
91     nativeClose(fd);
92   }
93
94   public int available() {
95     return nativeAvailable(fd);
96   }
97 }