Java 以编程方式检查最新版本

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12952699/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 10:56:43  来源:igfitidea点击:

Java check latest version programmatically

java

提问by Chris

Goal: check java's version on a machine (I can get this from java -version). Compare it with latest available from java website

目标:检查机器上的 java 版本(我可以从 中获得java -version)。将其与Java 网站上的最新版本进行比较

I would like to know if there is any way I can check for latest Java releases assuming that I have JRE/JDK installed on a machine.

我想知道是否有任何方法可以检查最新的 Java 版本,假设我在机器上安装了 JRE/JDK。

If I can do this through Java itself, my solution would become platform independent. I could use java.net.URLclass to send a request to Java website and get the HTML, however the response would be dynamic as Oracle can change their website and styles and possibly will have maintenance issues in long run.

如果我可以通过 Java 本身做到这一点,我的解决方案将独立于平台。我可以使用java.net.URLclass 向 Java 网站发送请求并获取 HTML,但是响应将是动态的,因为 Oracle 可以更改他们的网站和样式,并且从长远来看可能会出现维护问题。

I have looked at javatester.org, but I would not want it through an applet but through command line (which I can add to a script).

我看过javatester.org,但我不想通过小程序而是通过命令行(我可以将其添加到脚本中)。

Through javacpl.exe, I can schedule periodic checks, but I would like to do it on demand.

通过javacpl.exe,我可以安排定期检查,但我想按需进行。

采纳答案by Marcel St?r

The answer is actually quite simple. http://java.com/en/download/testjava.jspissues a request to http://java.com/applet/JreCurrentVersion2.txt. That file currently contains a single version number: '1.7.0_11'...which is the latest and greatest, indeed.

答案其实很简单。http://java.com/en/download/testjava.jsphttp://java.com/applet/JreCurrentVersion2.txt发出请求。该文件当前包含一个版本号:'1.7.0_11'...确实是最新和最好的。

Java code example

Java代码示例

try (BufferedReader br = new BufferedReader(new InputStreamReader(new URL(
    "http://java.com/applet/JreCurrentVersion2.txt").openStream()))) {
  String fullVersion = br.readLine();
  String version = fullVersion.split("_")[0];
  String revision = fullVersion.split("_")[1];
  System.out.println("Version " + version + " revision " + revision);
} catch (IOException e) {
  // handle properly
}

Update 2014-03-20

更新 2014-03-20

Eventhough Java 8 was recently releasedhttp://java.com/applet/JreCurrentVersion2.txtcurrently still returns 1.7.0_51.

尽管Java 8 最近发布了http://java.com/applet/JreCurrentVersion2.txt目前仍然返回 1.7.0_51。

Update 2016-07-13

更新 2016-07-13

Looks like we need to come back to this every few months... Currently you need to scan http://java.com/en/download/installed8.jspfor a JavaScript variable latest8Version. So, you could run curl -s https://java.com/en/download/installed8.jsp | grep latest8Version.

看起来我们需要每隔几个月回来一次...目前您需要扫描http://java.com/en/download/installed8.jsp以获取 JavaScript 变量latest8Version。所以,你可以运行curl -s https://java.com/en/download/installed8.jsp | grep latest8Version.

Update 2018-08-19

更新 2018-08-19

http://javadl-esd-secure.oracle.com/update/baseline.versionis another hot spot as mentioned in some other answer.

http://javadl-esd-secure.oracle.com/update/baseline.version是其他一些答案中提到的另一个热点。

回答by Sarel Botha

UPDATE: I don't recommend this method because this JRE is the one that has the Ask.com toolbar. You're better off downloading it yourself and distributing it yourself.

更新:我不推荐这种方法,因为这个 JRE 是具有 Ask.com 工具栏的那个。您最好自己下载并分发它。

The jusched.exe program accesses the following URL to find out what versions are available. I think it's less likely to change because jusched is installed on millions of computers.

jusched.exe 程序访问以下 URL 以找出可用的版本。我认为它不太可能改变,因为 jusched 安装在数百万台计算机上。

https://javadl-esd-secure.oracle.com/update/1.7.0/map-m-1.7.0.xml

https://javadl-esd-secure.oracle.com/update/1.7.0/map-m-1.7.0.xml

Here is a snippet of what it returns for me:

这是它为我返回的内容的片段:

<?xml version="1.0" encoding="ISO-8859-1" standalone="yes" ?>

<java-update-map version="1.0">
      <mapping>
      <version>1.7.0_17</version>
      <url>https://javadl-esd-secure.oracle.com/update/1.7.0/au-descriptor-1.7.0_25-b17.xml</url>
   </mapping>
   <mapping>
      <version>1.7.0_21</version>
      <url>https://javadl-esd-secure.oracle.com/update/1.7.0/au-descriptor-1.7.0_25-b17.xml</url>
   </mapping>
   </java-update-map>

To get the actual version that it is pointing to you have to fetch the above URL. Here is another snippet of what this XML looks like:

要获得它指向的实际版本,您必须获取上述 URL。下面是这个 XML 的另一个片段:

xml version="1.0" encoding="UTF-8" standalone="yes"?>
<!-- XML file to be staged anywhere, and pointed to by map.xml file -->
<java-update>
  <information version="1.0" xml:lang="en">
    <caption>Java Update - Update Available</caption>
    <title>Java Update Available</title>
    <description>Java 7 Update 25 is ready to install. Installing Java 7 Update 25 might uninstall the latest Java 6 from your system. Click the Install button to update Java now.  If you wish to update Java later, click the Later button.</description>
    <moreinfo>http://java.com/moreinfolink</moreinfo>
    <AlertTitle>Java Update Available</AlertTitle>
    <AlertText>A new version of Java is ready to be installed.</AlertText>
    <moreinfotxt>More information...</moreinfotxt>
    <url>http://javadl.sun.com/webapps/download/GetFile/1.7.0_25-b17/windows-i586/jre-7u25-windows-i586-iftw.exe</url>
    <version>1.7.0_25-b17</version>
    <post-status>https://nometrics.java.com</post-status>
    <cntry-lookup>http://rps-svcs.sun.com/services/countrylookup</cntry-lookup>
    <predownload></predownload>
    <options>/installmethod=jau FAMILYUPGRADE=1 SPWEB=http://javadl-esd.sun.com/update/1.7.0/sp-1.7.0_25-b17</options>
    <urlinfo>24595ec7f861bc67e572f1e4ad3992441335e1a7</urlinfo>
  </information>
</java-update>

The version tag contains the full version number.

版本标签包含完整的版本号。

回答by Juck Keng Lam

An URL very similar to the now defunct "JreCurrentVersion2.txt":

一个与现已失效的“JreCurrentVersion2.txt”非常相似的 URL:

http://javadl-esd-secure.oracle.com/update/baseline.version

http://javadl-esd-secure.oracle.com/update/baseline.version

The contents of the link look like this:

链接的内容如下所示:

1.8.0_111
1.7.0_121
1.6.0_131
1.5.0_99
1.4.2_43

You can easily parse the contents to find the latest JRE versions.

您可以轻松解析内容以找到最新的 JRE 版本。

回答by VonC

You could parse the Java SE Downloads pageto extract the Java versions.
That way, you get the version of both JDK6 and JDK7, which allows you to test your particular JDK (6 or 7) against the latest Oracle one.
(As opposed to the Free Java Download page, which only lists the JDK7)

您可以解析Java SE 下载页面以提取 Java 版本。
这样,您将获得 JDK6 和 JDK7 的版本,这允许您针对最新的 Oracle 测试您的特定 JDK(6 或 7)。
(与仅列出 JDK7的免费 Java 下载页面相反)

Her is a crudescript in Go, which you can compile on Windows, Unix, MacOs into a single independent executable, and use within a command line or a script:

她是一个粗糙的脚本,你可以在Windows,Unix,Mac系统编译成一个独立的可执行文件,命令行或脚本中使用:

package main

import (
    "bytes"
    "encoding/xml"
    "fmt"
    "io/ioutil"
    "net/http"
    "os/exec"
    "regexp"
)

type Jdk struct {
    Url    string
    Ver    string
    update string
}

func main() {
    resp, err := http.Get("http://www.oracle.com/technetwork/java/javase/downloads/index.html")
    if err != nil {
        fmt.Printf("Error on http Get: %v\n", err)
        return
    }
    bodyb, err := ioutil.ReadAll(resp.Body)
    if err != nil {
        fmt.Printf("QueriesForOwner: error in ReadAll: %v\n", err)
        return
    }
    br := bytes.NewBuffer(bodyb)
    jdkre, err := regexp.Compile(`h3[^\r\n]+(/technetwork/java/javase/downloads/(jdk(?:6|7)(?:u(\d+))?)-downloads-\d+\.html)`)
    if err != nil {
        fmt.Printf("extract: error in regexp compilation: %v\n", err)
        return
    }
    jdks := jdkre.FindAllSubmatch(br.Bytes(), -1)
    jdk7 := Jdk{string(jdks[0][4]), string(jdks[0][5]), string(jdks[0][6])}
    jdk6 := Jdk{string(jdks[1][7]), string(jdks[1][8]), string(jdks[1][9])}
    fmt.Printf("Jdk7: %v\nJdk6: %v\n", jdk7, jdk6)
    jver, err := exec.Command("java", "-version").CombinedOutput()
    if err != nil {
        fmt.Printf("*ExitError from java -version:", err)
        return
    }
    fmt.Println("JVer: '", string(jver), "'")
    jverre, err := regexp.Compile(`1.(\d).\d(?:_(\d+))"`)
    jvers := jverre.FindSubmatch(jver)
    jj := string(jvers[0])
    jv := string(jvers[1])
    ju := string(jvers[2])
    jdk := jdk6
    if jv == "7" {
        jdk = jdk7
    }
    if jdk.update != ju {
        fmt.Println("Local JDK *NOT* up-to-date: you have ", jj, ", Oracle has ", jdk.Ver)
    } else {
        fmt.Println("Local JDK *up-to-date*: you have ", jj, ", equals to Oracle, which has", jdk.Ver)
    }
}

Again, this is a crudescript, oriented toward JDK, and you would need to adapt it to your specific need, making its output and exit status match what you need for your script.

同样,这是一个面向 JDK的粗略脚本,您需要根据您的特定需要调整它,使其输出和退出状态与您的脚本需要的相匹配。

On my (PC) workstation, it returns:

在我的(PC)工作站上,它返回:

Jdk7: {/technetwork/java/javase/downloads/jdk7u9-downloads-1859576.html jdk7u9 9}
Jdk6: {/technetwork/java/javase/downloads/jdk6u37-downloads-1859587.html jdk6u37 37}
JVer: ' java version "1.6.0_31"
Java(TM) SE Runtime Environment (build 1.6.0_31-b05)
Java HotSpot(TM) Client VM (build 20.6-b01, mixed mode, sharing)
 '
Local JDK *NOT* up-to-date: you have  1.6.0_31" , Oracle has  jdk6u37

回答by Gijs Overvliet

I don't know what information you are exactly looking for, but you can get some version information using

我不知道您正在寻找什么信息,但是您可以使用以下方法获取一些版本信息

System.getProperty("java.version");

If this is not what you're looking for, check the other available properties here: http://docs.oracle.com/javase/6/docs/api/java/lang/System.html#getProperties()

如果这不是您要查找的内容,请在此处检查其他可用属性:http: //docs.oracle.com/javase/6/docs/api/java/lang/System.html#getProperties()

As for the latest available version, I guess you'd have to parse this site manually: http://java.com/en/download/index.jsp

至于最新的可用版本,我想您必须手动解析此站点:http: //java.com/en/download/index.jsp

The latest version is on there, currently it's

最新版本在那里,目前是

Version 7 Update 9

版本 7 更新 9

You write that this is not what you want because "Oracle can change their website and styles". However, you want to find out the latest version of Java by accessing their service (website in this case). As long as you're not paying for this, they have no obligation to you, and can change the service whenever they want without your consent. And even when you're a paying customer, the best you can hope for is that they will inform you of upcoming changes, and your maintenance issues will remain.

您写道这不是您想要的,因为“Oracle 可以更改他们的网站和样式”。但是,您想通过访问他们的服务(在这种情况下是网站)来找出最新版本的 Java。只要您不为此付费,他们就对您没有义务,并且可以在未经您同意的情况下随时更改服务。即使您是付费客户,您所能希望的最好的事情就是他们会通知您即将发生的变化,而您的维护问题仍然存在。

Remember, it's THEIR service you want to use.

请记住,您要使用的是他们的服务。

回答by jalopaba

I have solved a similar issue some time ago with this groovy script (disclaimer: is somehow a "toy" script):

前段时间我用这个 groovy 脚本解决了一个类似的问题(免责声明:某种程度上是一个“玩具”脚本):

@Grapes([
    @Grab(group='org.ccil.cowan.tagsoup', module='tagsoup', version='1.2.1')
])

def slurper = new XmlSlurper(new org.ccil.cowan.tagsoup.Parser())
def url = new URL("http://www.java.com/download/manual.jsp")

def html
url.withReader { reader ->
    html = slurper.parse(reader)
}
def lastJava = html.body.div.div.div.strong.text()

println "Last available java version: ${lastJava}"
println "Currently installed java version: ${System.properties["java.version"]}"

It yields something like:

它产生类似的东西:

Last available java version: 
Version 7 Update 9

Currently installed java version: 1.7.0_07

If you want to avoid maintenance issues due to changes to the page structure, maybe a better option is to search for a line containing "Version x Update y".

如果您想避免由于页面结构更改而导致的维护问题,也许更好的选择是搜索包含“Version x Update y”的行。

回答by Madan Sapkota

To get all system variables

获取所有系统变量

Properties properties = System.getProperties();
System.out.println(properties);

Sample output, this might be different in your system depending on your OS and Java JDK/JRE version.

示例输出,这在您的系统中可能会有所不同,具体取决于您的操作系统和 Java JDK/JRE 版本。

{
    java.runtime.name = Java(TM) SE Runtime Environment,
    sun.boot.library.path = C:\Program Files\Java\jdk1.8.0_31\jre\bin,
    java.vm.version = 25.31-b07,
    java.vm.vendor = Oracle Corporation,
    java.vendor.url = http://java.oracle.com/,
    path.separator = ;,
    idea.launcher.port = 7534,
    java.vm.name = Java HotSpot(TM) 64-Bit Server VM,
    file.encoding.pkg = sun.io,
    user.country = NP,
    user.script = ,
    sun.java.launcher = SUN_STANDARD,
    sun.os.patch.level = ,
    java.vm.specification.name = Java Virtual Machine Specification,
    user.dir = C:\Users\...\roid,
    java.runtime.version = 1.8.0_31-b13,
    java.awt.graphicsenv = sun.awt.Win32GraphicsEnvironment,
    java.endorsed.dirs = C:\Program Files\Java\jdk1.8.0_31\jre\lib\endorsed,
    os.arch = amd64,
    java.io.tmpdir = C:\Windows\TEMP\,
    line.separator = ,
    java.vm.specification.vendor = Oracle Corporation,
    user.variant = ,
    os.name = Windows 8.1,
    sun.jnu.encoding = Cp1252,
    java.library.path = C:\Program...roid,
    java.specification.name = Java Platform API Specification,
    java.class.version = 52.0,
    sun.management.compiler = HotSpot 64-Bit Tiered Compilers,
    os.version = 6.3,
    user.home = C:\Users\Xxx,
    user.timezone = Asia/Kathmandu,
    java.awt.printerjob = sun.awt.windows.WPrinterJob,
    file.encoding = UTF-8,
    idea.launcher.bin.path = C:\Program Files (x86)\xxx\bin,
    java.specification.version = 1.8,
    java.class.path = C:\Program Files\Java\jdk1.8.0_31\jre\lib\charsets.jar;...,
    user.name = Xxx,
    java.vm.specification.version = 1.8,
    sun.java.command = com.xxxx.ameras,
    java.home = C:\Program Files\Java\jdk1.8.0_31\jre,
    sun.arch.data.model = 64,
    user.language = en,
    java.specification.vendor = Oracle Corporation,
    awt.toolkit = sun.awt.windows.WToolkit,
    java.vm.info = mixed mode,
    java.version = 1.8.0_31,
    java.ext.dirs = C:\Program Files\Java\jdk1.8.0_31\jre\lib\ext;...,
    java.vendor = Oracle Corporation,
    file.separator = \,
    java.vendor.url.bug = http://bugreport.sun.com/bugreport/,
    sun.io.unicode.encoding = UnicodeLittle,
    sun.cpu.endian = little,
    sun.desktop = windows,
    sun.cpu.isalist = amd64
}

Retrive only specific variable

仅检索特定变量

String javaVersion = System.getProperty("java.version");
System.out.println(javaVersion);

Output

输出

1.8.0_31

回答by l0b0

@MarcelSt?r's solutionno longer works - the version in the fileis 1.8.0_51, while the actual latest version is 1.8.0_91/92.If you go to the Java test pagein Firefox or Chrome and open the development console you can get the variable latest8Versionwhich currently is 1.8.0_91. This could be wrapped in a Selenium/Firefox solution, but is an incredibly hacky way of getting this information.

@MarcelSt?r 的解决方案不再有效——文件中的版本是 1.8.0_51,而实际的最新版本是 1.8.0_91/92。如果您在 Firefox 或 Chrome 中转到Java 测试页面并打开开发控制台,您可以获得latest8Version当前为1.8.0_91. 这可以包含在 Selenium/Firefox 解决方案中,但这是获取此信息的一种令人难以置信的黑客方式。

回答by Vishal Chaudhari

System.getProperty("java.vm.specification.version");
System.getProperty("java.version");