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