1 24 25 package com.mckoi.store; 26 27 import java.io.File ; 28 import java.io.SyncFailedException ; 29 import java.io.RandomAccessFile ; 30 import java.io.IOException ; 31 32 38 39 class IOStoreDataAccessor implements StoreDataAccessor { 40 41 44 private Object lock = new Object (); 45 46 49 private File file; 50 51 54 private RandomAccessFile data; 55 56 59 private long size; 60 61 64 private boolean is_open; 65 66 69 IOStoreDataAccessor(File file) { 70 this.file = file; 71 this.is_open = false; 72 } 73 74 76 public void open(boolean is_read_only) throws IOException { 77 synchronized (lock) { 78 data = new RandomAccessFile (file, is_read_only ? "r" : "rw"); 79 size = file.length(); 80 is_open = true; 81 } 82 } 83 84 public void close() throws IOException { 85 synchronized (lock) { 86 data.close(); 87 data = null; 88 is_open = false; 89 } 90 } 91 92 public boolean delete() { 93 if (!is_open) { 94 return file.delete(); 95 } 96 return false; 97 } 98 99 public boolean exists() { 100 return file.exists(); 101 } 102 103 104 public void read(long position, byte[] buf, int off, int len) 105 throws IOException { 106 synchronized (lock) { 108 len = Math.max(0, Math.min(len, (int) (size - position))); 109 if (position < size) { 110 data.seek(position); 111 data.readFully(buf, off, len); 112 } 113 } 114 } 115 116 public void write(long position, byte[] buf, int off, int len) 117 throws IOException { 118 synchronized (lock) { 120 len = Math.max(0, Math.min(len, (int) (size - position))); 121 if (position < size) { 122 data.seek(position); 123 data.write(buf, off, len); 124 } 125 } 126 } 127 128 public void setSize(long new_size) throws IOException { 129 synchronized (lock) { 130 if (new_size > this.size) { 132 long p = new_size - 1; 135 if (p > 0) { 136 data.seek(p); 137 data.write(0); 138 this.size = new_size; 139 } 140 } 141 else if (new_size < this.size) { 142 data.setLength(new_size); 148 this.size = new_size; 149 } 150 } 151 } 152 153 public long getSize() throws IOException { 154 synchronized (lock) { 155 if (is_open) { 156 return size; 157 } 158 else { 159 return file.length(); 160 } 161 } 162 } 163 164 public void synch() throws IOException { 165 synchronized (lock) { 166 try { 167 data.getFD().sync(); 168 } 169 catch (SyncFailedException e) { 170 } 174 } 175 } 176 177 178 } 179 180 | Popular Tags |