- /**
- * Opens the cache in {@code directory}, creating a cache if none exists
- * there.
- *
- * @param directory a writable directory
- * @param appVersion
- * @param valueCount the number of values per cache entry. Must be positive. 每份缓存限定字节数
- * @param maxSize the maximum number of bytes this cache should use to store 文件缓存总字节数
- * @throws IOException if reading or writing the cache directory fails
- */
//理解 本方法就是要创建一个对于磁盘文件的LruDiskCache
throws IOException {
if (maxSize <= 0) {
throw new IllegalArgumentException("maxSize <= 0");
}
if (valueCount <= 0) {
throw new IllegalArgumentException("valueCount <= 0");
}
// 是否存在备份文件
File backupFile = new File(directory, JOURNAL_FILE_BACKUP);
if (backupFile.exists()) {
File journalFile = new File(directory, JOURNAL_FILE);
// 如果正常文件存在就删除备份文件
if (journalFile.exists()) {
backupFile.delete();
} else {
renameTo(backupFile, journalFile, false);
}
}
// 读取每个缓存
LruDiskCache cache = new LruDiskCache(directory, appVersion, valueCount, maxSize);
if (cache.journalFile.exists()) {
try {
cache.readJournal();
cache.processJournal();
cache.journalWriter = new BufferedWriter(
new OutputStreamWriter(new FileOutputStream(cache.journalFile, true), HTTP.US_ASCII));
return cache;
} catch (Throwable journalIsCorrupt) {
LogUtils.e("LruDiskCache"
+ directory
+ " is corrupt: "
+ journalIsCorrupt.getMessage()
+ ", removing", journalIsCorrupt);
cache.delete();
}
}
// 创建一个新的空的缓存
if (directory.exists() || directory.mkdirs()) {
cache = new LruDiskCache(directory, appVersion, valueCount, maxSize);
cache.rebuildJournal();
}
return cache;
}