[英]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. 我正在构建一个Java小程序,其中涉及从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.
我发现图像已被缓存,可以在Java控制面板的“ Internet临时文件” /“查看...” /“资源”下查看它们。 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.
不幸的是,我需要能够更新图像并使这些更新出现在applet的执行之间,但是缓存引起了问题。
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). 如果相关,我将使用以下代码下载图像:(mt是MediaTracker对象)。
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: 如果要控制到期时间,可以通过添加以下行来专门设置
Cache-Control
或Expires
标头:
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. 使用
URLConnection
将图像下载到byte
数组中。 Pass this byte
array to createImage()
. 将此
byte
数组传递给createImage()
。 You may also want to turn off caching by calling setUseCaches(false)
on the URLConnection
object. 您可能还想通过在
URLConnection
对象上调用setUseCaches(false)
来关闭缓存。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.