44d888923eb697d4d1c7b5fd2987511a0e9970e4
[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
20   public int read() {
21     byte b[]=new byte[1];
22     int retval=read(b);
23     if (retval==-1 || retval==0)
24       return -1;
25
26     // if carriage return comes back, dump it
27     if( b[0] == 13 ) {
28       return read();
29     }
30
31     // otherwise return result
32     return b[0];
33   }
34
35   public int peek() {
36     return nativePeek(fd);
37   }
38
39   public int read(byte[] b) {
40     return nativeRead(fd, b, b.length);
41   }
42
43   public String readLine() {
44     String line = "";
45     int c = read();
46
47     // if we're already at the end of the file
48     // or there is an error, don't even return
49     // the empty string
50     if( c <= 0 ) {
51       return null;
52     }
53
54     // ASCII 13 is carriage return, check for that also
55     while( c != '\n' && c != 13 && c > 0 ) {
56       line += (char)c;
57       c = read();
58     }
59
60     // peek and consume characters that are carriage
61     // returns or line feeds so the whole line is read
62     // and returned, and none of the line-ending chars
63     c = peek();
64     while( c == '\n' || c == 13 ) {
65       c = read();
66       c = peek();
67     }
68
69     return line;
70   }
71
72   public void close() {
73     nativeClose(fd);
74   }
75 }