gpt4 book ai didi

java - 关闭 JarURLConnection

转载 作者:行者123 更新时间:2023-11-29 02:58:49 26 4
gpt4 key购买 nike

使用 JarURLConnection,我可以使用以下代码结构从 托管在 Dropbox 上的 JAR 中读取文件(例如 version.txt):

public static void checkForUpdates() {
JarURLConnection jarConn = null;
try {

System.out.println("Checking for updates..");

URL updateURL = new URL("jar:https://www.dropbox.com/s/.../foo.jar?dl=1!/version.txt");
jarConn = (JarURLConnection) updateURL.openConnection();
JarFile jarFile = jarConn.getJarFile();
InputStream inputStream = jarFile.getInputStream(jarConn.getJarEntry());
BufferedReader versionTXT = new BufferedReader(new InputStreamReader(inputStream));

/* Version comparing left out */

// If there is an update:
System.out.println("Update found!");

} catch (IOException e) {
e.printStackTrace();
} finally {
if (jarConn != null) {
// This doesn't seem to work
jarConn.getInputStream().close();
}
}
}

当我第一次调用这个方法时,它工作正常;您可以看到“检查更新”消息和“结果”消息之间的延迟。

当我在 Dropbox 上上传新的 foo.jar 并再次运行 checkForUpdates() 方法时(没有重新启动 JVM),它将使用“旧”jar,并且没有延迟在检查和结果消息之间。当我确实重新启动 JVM 时,它将使用"new"jar 并显示消息之间的延迟。

有什么方法可以关闭 JarURLConnection,而不是关闭 InputStream(这似乎不起作用)?

我尝试了以下方法:

  • 关闭 JarURLConnection 的 OutputStream -> 抛出一个错误,指出连接没有 OutputStream。
  • 关闭 URLConnections Input- & OutputStream(通过在我将它转换为 JarURLConnection 之前创建一个新变量)-> 关闭 InputStream 似乎没有做任何事情,关闭 OutputStream 抛出相同的错误。
  • 关闭 BufferedReader -> 无效。

如果无法关闭 JarURLConnection,是否可以创建一个可以重新连接的新连接?重新启动 JVM 显然会做一些它会重新连接的事情,是否可以重新启动 JVM 来模拟?

提前致谢。

最佳答案

JarURLConnection 使用 jar 文件的缓存。因此,您不会在第二次尝试中看到任何延迟。

因此在访问 Jar 文件之前只需关闭缓存即可:

JarURLConnection con = ...;
con.setUseCaches(false);
JarFile jarFile = jarConn.getJarFile();

关于java - 关闭 JarURLConnection,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36517604/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com