1 29 30 package com.caucho.quercus.lib.file; 31 32 import com.caucho.quercus.env.Env; 33 import com.caucho.quercus.env.Value; 34 import com.caucho.vfs.FilePath; 35 import com.caucho.vfs.Path; 36 37 import java.io.File ; 38 import java.io.IOException ; 39 import java.io.RandomAccessFile ; 40 import java.nio.channels.FileChannel ; 41 import java.nio.channels.FileLock ; 42 import java.util.logging.Logger ; 43 44 47 public class FileInput extends ReadStreamInput implements LockableStream { 48 private static final Logger log 49 = Logger.getLogger(FileInput.class.getName()); 50 51 private Env _env; 52 private Path _path; 53 private FileLock _fileLock; 54 private FileChannel _fileChannel; 55 56 public FileInput(Env env, Path path) 57 throws IOException 58 { 59 _env = env; 60 61 _path = path; 62 63 init(path.openRead()); 64 } 65 66 69 public Path getPath() 70 { 71 return _path; 72 } 73 74 77 public BinaryInput openCopy() 78 throws IOException 79 { 80 return new FileInput(_env, _path); 81 } 82 83 86 public long getLength() 87 { 88 return getPath().getLength(); 89 } 90 91 public long seek(long offset, int whence) 92 { 93 switch (whence) { 94 case BinaryInput.SEEK_CUR: 95 offset = getPosition() + offset; 96 break; 97 case BinaryInput.SEEK_END: 98 offset = getLength() + offset; 99 break; 100 case SEEK_SET: 101 default: 102 break; 103 } 104 105 setPosition(offset); 106 107 return offset; 108 } 109 110 113 public boolean lock(boolean shared, boolean block) 114 { 115 if (! (getPath() instanceof FilePath)) 116 return false; 117 118 try { 119 File file = ((FilePath) getPath()).getFile(); 120 121 if (_fileChannel == null) { 122 RandomAccessFile randomAccessFile = new RandomAccessFile (file, "rw"); 123 124 _fileChannel = randomAccessFile.getChannel(); 125 } 126 127 if (block) 128 _fileLock = _fileChannel.lock(0, Long.MAX_VALUE, shared); 129 else 130 _fileLock = _fileChannel.tryLock(0, Long.MAX_VALUE, shared); 131 132 return _fileLock != null; 133 } catch (IOException e) { 134 return false; 135 } 136 } 137 138 141 public boolean unlock() 142 { 143 try { 144 if (_fileLock != null) { 145 _fileLock.release(); 146 147 return true; 148 } 149 150 return false; 151 } catch (IOException e) { 152 return false; 153 } 154 } 155 156 public Value stat() 157 { 158 return FileModule.statImpl(_env, getPath()); 159 } 160 161 164 public String toString() 165 { 166 return "FileInput[" + getPath() + "]"; 167 } 168 } 169 170 | Popular Tags |