1 29 30 package com.caucho.quercus.lib.file; 31 32 import com.caucho.quercus.env.StringValue; 33 import com.caucho.quercus.env.StringValueImpl; 34 import com.caucho.vfs.Path; 35 import com.caucho.vfs.ReadStream; 36 37 import java.io.IOException ; 38 import java.io.OutputStream ; 39 import java.util.logging.Level ; 40 import java.util.logging.Logger ; 41 42 45 public class FileReadValue extends FileValue { 46 private static final Logger log 47 = Logger.getLogger(FileReadValue.class.getName()); 48 49 private ReadStream _is; 50 private long _offset; 51 52 public FileReadValue(Path path) 53 throws IOException 54 { 55 super(path); 56 57 _is = path.openRead(); 58 } 59 60 63 public long getLength() 64 { 65 return getPath().getLength(); 66 } 67 68 71 public int read() 72 throws IOException 73 { 74 if (_is != null) { 75 int v = _is.read(); 76 77 if (v >= 0) 78 _offset++; 79 else 80 close(); 81 82 return v; 83 } 84 else 85 return -1; 86 } 87 88 91 public int read(byte []buffer, int offset, int length) 92 throws IOException 93 { 94 if (_is != null) { 95 int len = _is.read(buffer, offset, length); 96 97 if (len >= 0) 98 _offset += len; 99 else 100 close(); 101 102 return len; 103 } 104 else 105 return -1; 106 } 107 108 111 public boolean readOptionalLinefeed() 112 throws IOException 113 { 114 if (_is != null) { 115 int ch = _is.read(); 116 117 if (ch == '\n') { 118 _offset++; 119 return true; 120 } 121 else { 122 _is.unread(); 123 return false; 124 } 125 } 126 else 127 return false; 128 } 129 130 @Override 131 public void writeToStream(OutputStream os, int length) 132 throws IOException 133 { 134 if (_is != null) { 135 _is.writeToStream(os, length); 136 } 137 } 138 139 142 public StringValue readLine() 143 throws IOException 144 { 145 147 if (_is != null) 148 return new StringValueImpl(_is.readLineNoChop()); 149 else 150 return null; 151 } 152 153 156 public boolean isEOF() 157 { 158 if (_is == null) 159 return true; 160 else { 161 try { 162 return _is.available() <= 0; 164 } catch (IOException e) { 165 log.log(Level.FINE, e.toString(), e); 166 167 return true; 168 } 169 } 170 } 171 172 175 public long getPosition() 176 { 177 if (_is == null) 178 return -1; 179 else 180 return _is.getPosition(); 181 } 182 183 186 public void close() 187 { 188 ReadStream is = _is; 189 _is = null; 190 191 if (is != null) 192 is.close(); 193 } 194 195 199 public String toString() 200 { 201 return "File[" + getPath() + "]"; 202 } 203 204 } 205 206 | Popular Tags |