1 32 package com.imagero.uio.buffer.fm; 33 34 import com.imagero.uio.buffer.MutableRAFBufferManager; 35 import com.imagero.uio.buffer.Buffer; 36 import com.imagero.uio.buffer.RAFBuffer; 37 import com.imagero.uio.io.IOutils; 38 import com.imagero.uio.Sys; 39 40 import java.io.File ; 41 import java.io.IOException ; 42 import java.io.RandomAccessFile ; 43 import java.awt.event.ActionListener ; 44 import java.awt.event.ActionEvent ; 45 46 50 class FMBufferManager extends MutableRAFBufferManager { 51 52 File file; 53 ActionListener listener; 54 volatile boolean reading, writing; 55 56 public FMBufferManager(File file, ActionListener listener) throws IOException { 57 super(new RandomAccessFile (file, "rw")); 58 this.listener = listener; 59 this.file = file; 60 } 61 62 public FMBufferManager(RandomAccessFile raf) throws IOException { 63 super(raf); 64 } 65 66 protected Buffer createBuffer(RandomAccessFile raf, long offset, int dsLength) { 67 long maxLength = 0; 68 try { 69 maxLength = raf.length() - offset; 70 } 71 catch (IOException ex) { 72 ex.printStackTrace(); 73 } 74 if (maxLength < 0) { 75 return new FMBuffer(raf, offset, 0); 76 } 77 return new FMBuffer(raf, offset, (int) Math.min(maxLength, dsLength)); 78 } 79 80 boolean canClose() { 81 return !reading && !writing; 82 } 83 84 void _close() { 85 super.close(); 86 listener = null; 87 file = null; 88 raf = null; 89 } 90 91 public void close() { 92 IOutils.closeStream(raf); 93 raf = null; 94 listener.actionPerformed(new ActionEvent (this, ActionEvent.ACTION_PERFORMED, OpenFileManager.CLOSE)); 95 if(OpenFileManager.debug && file != null) { 96 Sys.out.print("\nclose: "); 97 Sys.out.println(file.getAbsolutePath()); 98 } 99 } 100 101 private RandomAccessFile get() throws IOException { 102 if (file == null) { 103 throw new NullPointerException ("This stream cannot be reopened!"); 104 } 105 boolean opened = false; 106 if (raf == null) { 107 raf = new RandomAccessFile (file, "rw"); 108 listener.actionPerformed(new ActionEvent (this, ActionEvent.ACTION_PERFORMED, OpenFileManager.OPEN)); 109 opened = true; 110 if(OpenFileManager.debug && file != null) { 111 Sys.out.print("\nopen: "); 112 Sys.out.println(file.getAbsolutePath()); 113 } 114 } 115 if(!opened) { 116 listener.actionPerformed(new ActionEvent (this, ActionEvent.ACTION_PERFORMED, OpenFileManager.GET)); 117 } 118 return raf; 119 } 120 121 class FMBuffer extends RAFBuffer { 122 123 public FMBuffer(RandomAccessFile ra, long offset, int length) { 124 super(ra, offset, length); 125 } 126 127 protected void readData() throws IOException { 128 reading = true; 129 try { 130 raf = get(); 131 super.readData(); 132 } 133 finally { 134 reading = false; 135 } 136 } 137 138 protected void writeData() throws IOException { 139 writing = true; 140 try { 141 raf = get(); 142 super.writeData(); 143 } 144 finally { 145 writing = false; 146 } 147 } 148 } 149 } 150 | Popular Tags |