1 19 20 21 package org.netbeans.modules.editor.retouche; 22 23 import java.io.EOFException ; 24 import java.io.FileOutputStream ; 25 import java.io.IOException ; 26 import java.io.InputStream ; 27 28 import org.netbeans.editor.ext.DataAccessor; 29 import org.openide.filesystems.FileObject; 30 import org.openide.filesystems.FileUtil; 31 import org.openide.filesystems.FileLock; 32 33 43 public class FileObjectAccessor implements DataAccessor { 44 45 FileObject fo; 46 InputStream inputStream; 47 FileOutputStream fos; 48 int actOff; 49 50 public FileObjectAccessor(FileObject fo) { 51 this.fo = fo; 52 } 53 54 60 public void append(byte[] buffer, int off, int len) throws IOException { 61 fos = new FileOutputStream (FileUtil.toFile(fo).getPath(), true); 62 fos.write(buffer, off, len); 63 fos.flush(); 64 fos.close(); 65 fos = null; 66 } 67 68 79 public void read(byte[] buffer, int off, int len) throws IOException { 80 int n = 0; 81 off = actOff + off; 82 do { 83 int count = this.readStream(buffer, off + n, len - n); 84 if (count < 0) 85 throw new EOFException (); 86 n += count; 87 } while (n < len); 88 } 89 90 93 public void open(boolean requestWrite) throws IOException { 94 if (!fo.existsExt(fo.getExt())){ 95 resetFile(); 96 } 97 } 98 99 100 public void close() throws IOException { 101 if (inputStream!=null){ 102 inputStream.close(); 103 } 104 inputStream = null; 105 } 106 107 113 public long getFilePointer() throws IOException { 114 return actOff; 115 } 116 117 118 public void resetFile() throws IOException { 119 FileObject folder = fo.getParent(); 120 String name = fo.getName(); 121 String ext = fo.getExt(); 122 FileLock lock = fo.lock(); 123 try { 124 fo.delete(lock); 125 } finally { 126 lock.releaseLock(); 127 } 128 fo = folder.createData(name, ext); 129 actOff = 0; 130 } 131 132 136 public void seek(long pos) throws IOException { 137 actOff = (int)pos; 138 } 139 140 145 private int readStream(byte[] buffer, int off, int len) throws IOException { 146 int read = getStream(off).read(buffer,0,len); 147 actOff += read; 148 return read; 149 } 150 151 152 private InputStream getStream(int off) throws IOException { 153 if(inputStream == null) { 154 inputStream = fo.getInputStream(); 155 inputStream.skip(off); 156 } else { 157 if(off >= actOff) { 158 inputStream.skip(off-actOff); 159 } else { 160 inputStream.close(); 161 inputStream = fo.getInputStream(); 162 inputStream.skip(off); 163 } 164 } 165 actOff = off; 166 return inputStream; 167 } 168 169 public int getFileLength() { 170 return (int)fo.getSize(); 171 } 172 173 public String toString() { 174 return fo.toString(); 175 } 176 177 } 178 | Popular Tags |