|
24 | 24 | import java.io.ObjectOutputStream;
|
25 | 25 | import java.io.RandomAccessFile;
|
26 | 26 | import java.io.Serializable;
|
| 27 | +import java.nio.MappedByteBuffer; |
| 28 | +import java.nio.channels.FileChannel; |
27 | 29 | import java.util.Collections;
|
28 | 30 | import java.util.HashMap;
|
29 | 31 | import java.util.Locale;
|
@@ -192,20 +194,23 @@ public void put(String key, byte[] value, int saveTime) {
|
192 | 194 | public byte[] getBytes(String key) {
|
193 | 195 | File file = mCacheManager.getFile(key);
|
194 | 196 | if (!file.exists()) return null;
|
195 |
| - RandomAccessFile raf = null; |
| 197 | + FileChannel fc = null; |
196 | 198 | try {
|
197 |
| - raf = new RandomAccessFile(file, "r"); |
198 |
| - byte[] byteArray = new byte[(int) raf.length()]; |
199 |
| - raf.read(byteArray); |
200 |
| - if (!CacheHelper.isDue(byteArray)) { |
201 |
| - return CacheHelper.getDataWithoutDueTime(byteArray); |
| 199 | + fc = new RandomAccessFile(file, "r").getChannel(); |
| 200 | + MappedByteBuffer byteBuffer = fc.map(FileChannel.MapMode.READ_ONLY, 0, fc.size()).load(); |
| 201 | + byte[] data = new byte[(int) fc.size()]; |
| 202 | + if (byteBuffer.remaining() > 0) { |
| 203 | + byteBuffer.get(data, 0, byteBuffer.remaining()); |
| 204 | + } |
| 205 | + if (!CacheHelper.isDue(data)) { |
| 206 | + return CacheHelper.getDataWithoutDueTime(data); |
202 | 207 | } else {
|
203 | 208 | mCacheManager.remove(key);
|
204 | 209 | }
|
205 |
| - } catch (Exception e) { |
| 210 | + } catch (IOException e) { |
206 | 211 | e.printStackTrace();
|
207 | 212 | } finally {
|
208 |
| - CloseUtils.closeIO(raf); |
| 213 | + CloseUtils.closeIO(fc); |
209 | 214 | }
|
210 | 215 | return null;
|
211 | 216 | }
|
@@ -242,28 +247,7 @@ public void put(String key, String value, int saveTime) {
|
242 | 247 | * @return String
|
243 | 248 | */
|
244 | 249 | public String getString(String key) {
|
245 |
| - File file = mCacheManager.getFile(key); |
246 |
| - if (!file.exists()) return null; |
247 |
| - BufferedReader br = null; |
248 |
| - try { |
249 |
| - br = new BufferedReader(new InputStreamReader(new FileInputStream(file))); |
250 |
| - StringBuilder sb = new StringBuilder(); |
251 |
| - String line; |
252 |
| - while ((line = br.readLine()) != null) { |
253 |
| - sb.append(line).append(LINE_SEP); |
254 |
| - } |
255 |
| - String content = sb.toString(); |
256 |
| - if (!CacheHelper.isDue(content)) { |
257 |
| - return CacheHelper.getDataWithoutDueTime(content); |
258 |
| - } else { |
259 |
| - mCacheManager.remove(key); |
260 |
| - } |
261 |
| - } catch (IOException e) { |
262 |
| - e.printStackTrace(); |
263 |
| - } finally { |
264 |
| - CloseUtils.closeIO(br); |
265 |
| - } |
266 |
| - return null; |
| 250 | + return new String(getBytes(key)); |
267 | 251 | }
|
268 | 252 |
|
269 | 253 | ///////////////////////////////////////////////////////////////////////////
|
|
0 commit comments