How do you control the caching of resources in Java?
I am building a Java applet that involves downloading images among other resources from a URL. I have discovered that the images are being cached, and can view them in the Java Control Panel under Temporary Internet Files / View... / Resources. 开发者_StackOverflow中文版Unfortunately I need to be able to update the images and have these updates appear between executions of the applet but the cache is causing problems.
I can't find any information about what controls the caching of these kinds of resources. What process is caching the resources and how do I control it? In particular how do I set the expiry time for images, or perhaps even specific images?
In case it is relevant, I am downloading the images using code like this: (mt is a MediaTracker object).
public BufferedImage getImageFromUrl(String url)
{
Image img = null;
try {
URL u = new URL(url);
img = java.awt.Toolkit.getDefaultToolkit().createImage(u);
mt.addImage(img, numImages++);
mt.waitForAll();
...
Thanks for any help.
Use this to avoid cached images from the server:
URL u = new URL(url);
URLConnection con = u.openConnection();
con.setUseCaches(false);
img = Toolkit.getDefaultToolkit().createImage(new URLImageSource(u, con));
If you want control over the expiry time you can specifically set the Cache-Control
or Expires
headers by adding lines like:
con.addRequestProperty("Cache-Control", "no-cache, max-age=3600");
con.addRequestProperty("Expires", "Thu, 17 Mar 2011 01:34:00 GMT");
Use a URLConnection
to download the image into a byte
array. Pass this byte
array to createImage()
. You may also want to turn off caching by calling setUseCaches(false)
on the URLConnection
object.
精彩评论