Java中如何控制资源的缓存?
我正在构建一个 Java 小程序,它涉及从 URL 下载图像和其他资源。我发现图像正在被缓存,并且可以在 Java 控制面板中的临时 Internet 文件/查看.../资源下查看它们。不幸的是,我需要能够更新图像并让这些更新出现在小程序的执行之间,但缓存导致了问题。
我找不到任何有关控制此类资源缓存的信息。什么进程正在缓存资源以及如何控制它?特别是如何设置图像甚至特定图像的到期时间?
如果相关,我将使用如下代码下载图像:(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();
...
感谢您的任何帮助。
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. 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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
使用它可以避免来自服务器的缓存图像:
如果您想控制过期时间,您可以通过添加以下行来专门设置
Cache-Control
或Expires
标头:Use this to avoid cached images from the server:
If you want control over the expiry time you can specifically set the
Cache-Control
orExpires
headers by adding lines like:使用
URLConnection
将图像下载到byte
数组中。将此byte
数组传递给createImage()
。您可能还想通过在URLConnection
对象上调用setUseCaches(false)
来关闭缓存。Use a
URLConnection
to download the image into abyte
array. Pass thisbyte
array tocreateImage()
. You may also want to turn off caching by callingsetUseCaches(false)
on theURLConnection
object.