Class Cache

All Implemented Interfaces:
AutoCloseable

public class Cache extends ChilkatObject
<section class="cache-summary">

Store, retrieve, expire, and clean up cached text or binary data on disk.

Chilkat.Cache is a disk-based cache class for storing and retrieving text or binary items by unique key. It provides configurable cache roots, optional multi-level directory layout, expiration metadata, ETag metadata, cache lookup, fetch-status properties, expiration updates, and cleanup methods for deleting individual items, expired items, older items, or the entire cache.

Key-based storage

Store and retrieve cached items by unique key, without the application needing to manage the underlying cache filenames directly.

Text and binary data

Cache strings, byte data, files, or Chilkat buffer objects depending on the data form used by the application.

Expiration control

Associate cached items with expiration times, update expiration metadata, and check whether cached content is still usable.

ETag metadata

Store and retrieve ETag values for workflows that need HTTP-style cache validation or conditional re-fetch logic.

Configurable layout

Choose the cache root directory and use an optional multi-level directory structure to avoid too many files in a single folder.

Cleanup operations

Delete a single cached item, remove expired items, remove older items, or clear the entire cache when needed.

Common pattern: Configure the cache root, choose the key used to identify each item, check whether a valid cached copy exists, fetch or regenerate the content when needed, store it with expiration and optional ETag metadata, and periodically clean up expired or old cached items.

For an extended overview, see Cache Class Overview.

</section>

Instances hold a native Chilkat object: close them with ChilkatObject.close() (try-with-resources) when done; an unclosed instance is freed when it becomes unreachable.

See Also:
Online reference
  • Constructor Details

    • Cache

      public Cache()
      Creates a new Cache object.
  • Method Details

    • getLastEtagFetched

      public String getLastEtagFetched()
      Returns the ETag metadata associated with the most recently fetched cache item. An empty string means that the fetched item has no stored ETag.

      Read after a fetch: This property describes the item returned by the most recent successful fetch operation, such as fetchBd(String, BinData), fetchSb(String, StringBuilder), or fetchText(String).ETags are opaque metadata: The cache stores and returns the string but does not interpret it. Applications commonly use an HTTP ETag with conditional requests such as If-None-Match.

      Returns:
      the value of the LastEtagFetched property (read-only)
    • getLastExpirationFetchedStr

      public String getLastExpirationFetchedStr()
      Returns the expiration date and time stored for the most recently fetched cache item, formatted as an RFC 822-style Internet date. An empty string represents an item with no expiration date.

      Expiration is metadata: Fetching an expired item is still possible. Read getLastHitExpired() after the fetch to determine whether the returned entry is stale.

      Returns:
      the value of the LastExpirationFetchedStr property (read-only)
    • getLastHitExpired

      public boolean getLastHitExpired()
      Returns true when the expiration time of the most recently fetched item is earlier than the current system date and time; otherwise returns false.

      Expired does not mean deleted: Expiration marks an entry as stale. The file remains in the cache until it is replaced or removed by methods such as deleteAllExpired() or deleteFromCache(String).

      Returns:
      the value of the LastHitExpired property (read-only)
    • getLastKeyFetched

      public String getLastKeyFetched()
      Returns the application-defined key associated with the most recently fetched cache item.

      Keys are not limited to URLs: A canonicalized URL is a common key for cached web content, but any unique string may be used. Reusing a key causes a save operation to replace the existing item for that key.

      Returns:
      the value of the LastKeyFetched property (read-only)
    • getLevel

      public int getLevel()
      Gets or sets the number of directory levels used beneath each cache root. Valid values are 0, 1, and 2.

      Value Directory layout

      0 All cache files are stored directly in the cache root.

      1 Files are distributed among 256 first-level directories named 0 through 255.

      2 Files are distributed through two levels of 256 directories, allowing as many as 65,536 leaf directories per root.

      Configure before use: Use the same level when reopening an existing cache. Changing the layout does not reorganize previously stored files and can prevent the object from locating them through their keys.

      Returns:
      the value of the Level property
    • setLevel

      public void setLevel​(int value)
      Sets the Level property; see getLevel().
      Parameters:
      value - the new value
    • getNumRoots

      public int getNumRoots()
      Returns the number of cache-root directories that have been registered by calling addRoot(String).

      Multiple roots: A cache may span more than one directory or storage device. Configure the same root set when reopening a persistent cache so previously stored items remain discoverable.

      Returns:
      the value of the NumRoots property (read-only)
    • addRoot

      public void addRoot​(String path)
      Adds path as a root directory for the disk cache. Call this method once for each root that should participate in the cache.

      For example, a cache distributed across D:\cacheRoot, E:\cacheRoot, and F:\cacheRoot is configured by calling this method three times.

      Use dedicated writable directories: Cache cleanup methods can delete cache files beneath every configured root. Do not mix unrelated application files into a cache root.Persistent configuration: Recreate the same roots and getLevel() setting before accessing a cache created by an earlier process or application run.

      Parameters:
      path - the path argument (not null)
    • deleteAll

      public int deleteAll()
      Deletes every cache item from all configured roots and returns the number of cache files removed. Multi-level subdirectories are retained.

      Destructive operation: This cannot be limited to a key prefix or reversed. Use cache roots dedicated to Chilkat cache data.

      Returns:
      the result (see ChilkatObject.getLastMethodSuccess() where the description mentions failure)
    • deleteAllExpired

      public int deleteAllExpired()
      Deletes all cache items whose stored expiration time is earlier than the current system time and returns the number of files removed.

      Non-expiring entries remain: Items saved without an expiration date are not removed by this method.

      Returns:
      the result (see ChilkatObject.getLastMethodSuccess() where the description mentions failure)
    • deleteFromCache

      public void deleteFromCache​(String key)
      Deletes the cache item identified by key.

      Return value Meaning

      true The item was deleted, or no item existed for the key.

      false The item exists but could not be deleted, for example because of a filesystem permission or sharing error.

      Idempotent deletion: A missing key is not treated as an error, which makes it safe to call this method when the application merely wants to ensure that an item is absent.

      Parameters:
      key - the key argument (not null)
      Throws:
      ChilkatException - if the operation fails; ChilkatException.getLastErrorText() says why
    • deleteOlderDt

      public int deleteOlderDt​(DateTime dt)
      Deletes cache items older than the cutoff date and time supplied in dt.

      Returns the number of cache files deleted, or -1 if an error occurs.

      Different from expiration cleanup: Use deleteAllExpired() when the decision should be based specifically on each item's expiration metadata.

      Parameters:
      dt - the dt argument (not null)
      Returns:
      the result (see ChilkatObject.getLastMethodSuccess() where the description mentions failure)
    • deleteOlderStr

      public int deleteOlderStr​(String dateTimeStr)
      Deletes cache items older than the cutoff date and time supplied in dateTimeStr as an RFC 822-style Internet date string.

      Returns the number of cache files deleted, or -1 if an error occurs.

      Date format: A typical value is Mon, 03 Aug 2026 12:00:00 GMT. Use deleteOlderDt(DateTime) when the cutoff is already available as a CkDateTime.

      Parameters:
      dateTimeStr - the dateTimeStr argument (not null)
      Returns:
      the result (see ChilkatObject.getLastMethodSuccess() where the description mentions failure)
    • fetchBd

      public void fetchBd​(String key, BinData bd)
      Retrieves the binary item identified by key and loads its bytes into the BinData object supplied in bd.

      The key is application-defined, may contain any characters, and must uniquely identify the intended item.

      Check the return value: Use the destination only when this method returns true. A failed lookup or filesystem error returns false.Freshness: A successful fetch may return an expired item. Read getLastHitExpired() immediately afterward when stale data must not be used.

      Parameters:
      key - the key argument (not null)
      bd - the bd argument (not null)
      Throws:
      ChilkatException - if the operation fails; ChilkatException.getLastErrorText() says why
    • fetchSb

      public void fetchSb​(String key, StringBuilder sb)
      Retrieves the text item identified by key and loads its content into the StringBuilder supplied in sb.

      The key is application-defined, may contain any characters, and must uniquely identify the intended item.

      Check the return value: Use the destination only when this method returns true. A failed lookup or filesystem error returns false.Freshness: A successful fetch may return an expired item. Read getLastHitExpired() immediately afterward when stale data must not be used.

      Parameters:
      key - the key argument (not null)
      sb - the sb argument (not null)
      Throws:
      ChilkatException - if the operation fails; ChilkatException.getLastErrorText() says why
    • fetchText

      public String fetchText​(String key)
      Retrieves the text item identified by key and returns its string content.

      The key is application-defined, may contain any characters, and must uniquely identify the intended item.

      Freshness is separate: A successful fetch can return an expired entry. Read getLastHitExpired() immediately afterward when the application requires only fresh data.

      Parameters:
      key - the key argument (not null)
      Returns:
      the result (never null)
      Throws:
      ChilkatException - if the operation fails; ChilkatException.getLastErrorText() says why
    • getEtag

      public String getEtag​(String key)
      Returns the ETag metadata stored with the cache item identified by key.

      Opaque value: Chilkat does not parse or validate the ETag. An application may store any auxiliary string here, although HTTP entity tags are the common use case.

      Parameters:
      key - the key argument (not null)
      Returns:
      the result (never null)
      Throws:
      ChilkatException - if the operation fails; ChilkatException.getLastErrorText() says why
    • getExpirationStr

      public String getExpirationStr​(String url)
      Returns the expiration date and time stored for the item identified by url, formatted as an RFC 822-style Internet date string.

      Argument name: Some language bindings name url url for historical reasons. It is the cache key and does not need to be a URL.No-expiration entries: An empty stored expiration represents an item that does not expire automatically.

      Parameters:
      url - the url argument (not null)
      Returns:
      the result (never null)
      Throws:
      ChilkatException - if the operation fails; ChilkatException.getLastErrorText() says why
    • getFilename

      public String getFilename​(String key)
      Returns the absolute filesystem path of the cache file associated with key.

      Implementation detail: Treat the returned path as diagnostic information. Applications should normally read, update, and delete entries through the Cache API rather than modifying cache files directly.

      Parameters:
      key - the key argument (not null)
      Returns:
      the result (never null)
      Throws:
      ChilkatException - if the operation fails; ChilkatException.getLastErrorText() says why
    • getRoot

      public String getRoot​(int index)
      Returns the directory path of the cache root at zero-based index. Valid indexes range from 0 through getNumRoots() - 1.
      Parameters:
      index - the index argument
      Returns:
      the result (never null)
      Throws:
      ChilkatException - if the operation fails; ChilkatException.getLastErrorText() says why
    • isCached

      public boolean isCached​(String key)
      Returns true if an item exists for key, or false if the key is not present.

      Presence is not freshness: This method does not imply that the entry is unexpired. Fetch the item and examine getLastHitExpired(), or read its expiration metadata, when freshness matters.

      Parameters:
      key - the key argument (not null)
      Returns:
      the result; this method never throws ChilkatException
    • saveBd

      public void saveBd​(String key, String expiration, String etag, BinData bd)
      Stores the contents of bd as binary cache data under key. If the key already exists, its data and metadata are replaced.

      Argument Purpose

      key The unique application-defined cache key.

      expiration Expiration as an RFC 822-style Internet date string. Pass an empty string for no expiration.

      etag Optional ETag or application metadata. Pass an empty string when unused.

      bd The BinData containing the bytes to save.

      Expiration is not automatic deletion: An expired item remains present until it is replaced or explicitly removed. This permits stale-while-revalidate workflows but requires the application to check freshness.

      Parameters:
      key - the key argument (not null)
      expiration - the expiration argument (not null)
      etag - the etag argument (not null)
      bd - the bd argument (not null)
      Throws:
      ChilkatException - if the operation fails; ChilkatException.getLastErrorText() says why
    • saveTextDt

      public void saveTextDt​(String key, DateTime expireDateTime, String eTag, String itemTextData)
      Stores itemTextData as a text cache item under key, with the expiration date and time supplied in expireDateTime. If the key already exists, its data and metadata are replaced.

      eTag is optional ETag or application metadata and may be an empty string. The key may contain any characters and may be any length, but it must uniquely identify the item.

      Expiration does not delete: After the expiration time passes, the entry remains on disk and can still be fetched. Use getLastHitExpired() to detect staleness and a deletion method to remove it.

      Parameters:
      key - the key argument (not null)
      expireDateTime - the expireDateTime argument (not null)
      eTag - the eTag argument (not null)
      itemTextData - the itemTextData argument (not null)
      Throws:
      ChilkatException - if the operation fails; ChilkatException.getLastErrorText() says why
    • saveTextNoExpire

      public void saveTextNoExpire​(String key, String eTag, String itemTextData)
      Stores itemTextData as a non-expiring text cache item under key. If the key already exists, its data and metadata are replaced.

      eTag is optional ETag or application metadata and may be an empty string.

      Parameters:
      key - the key argument (not null)
      eTag - the eTag argument (not null)
      itemTextData - the itemTextData argument (not null)
      Throws:
      ChilkatException - if the operation fails; ChilkatException.getLastErrorText() says why
    • saveTextStr

      public void saveTextStr​(String key, String expireDateTime, String eTag, String itemTextData)
      Stores itemTextData as a text cache item under key, with expireDateTime providing the expiration time as an RFC 822-style Internet date string. If the key already exists, its data and metadata are replaced.

      eTag is optional ETag or application metadata and may be empty.

      Date alternatives: Use saveTextDt(String, DateTime, String, String) when the expiration is available as a CkDateTime, or saveTextNoExpire(String, String, String) for an entry without expiration.

      Parameters:
      key - the key argument (not null)
      expireDateTime - the expireDateTime argument (not null)
      eTag - the eTag argument (not null)
      itemTextData - the itemTextData argument (not null)
      Throws:
      ChilkatException - if the operation fails; ChilkatException.getLastErrorText() says why
    • updateExpirationDt

      public void updateExpirationDt​(String key, DateTime expireDateTime)
      Replaces the expiration date and time of the cache item identified by key with the CkDateTime value supplied in expireDateTime. The cached data and ETag are unchanged.

      Existing item required: This method updates metadata; it does not create a new cache entry when the key is absent.

      Parameters:
      key - the key argument (not null)
      expireDateTime - the expireDateTime argument (not null)
      Throws:
      ChilkatException - if the operation fails; ChilkatException.getLastErrorText() says why
    • updateExpirationStr

      public void updateExpirationStr​(String key, String expireDateTime)
      Replaces the expiration date and time of the cache item identified by key with the RFC 822-style Internet date string supplied in expireDateTime. The cached data and ETag are unchanged.

      Argument name: Some language bindings name key url; it is the cache key and does not need to be a URL. Use updateExpirationDt(String, DateTime) for a CkDateTime value.

      Parameters:
      key - the key argument (not null)
      expireDateTime - the expireDateTime argument (not null)
      Throws:
      ChilkatException - if the operation fails; ChilkatException.getLastErrorText() says why