Java检查Windows上是否安装了程序

问题描述 投票:0回答:4

有没有办法使用 Java 检查 Windows 上是否安装了特定程序?

我正在尝试开发一个 Java 程序,该程序可以使用 7-Zip 中的代码行命令自动创建 zip 存档。

因此,我想检查我的 Windows 操作系统上是否已安装 Java '7-Zip'。不检查正在运行的应用程序或操作系统是 Windows 还是 Linux。如果 Windows 上安装了“7-Zip”,我想得到一个布尔值(真/假)。

java windows zip
4个回答
0
投票

Apache Commons 库有一个名为

SystemUtils
的类 - 完整文档可在 https://commons.apache.org/proper/commons-lang/javadocs/api-2.6/org/apache/commons/lang/SystemUtils 获取.html

在此库中,您可以使用以下

static boolean
属性:

SystemUtils.IS_OS_LINUX
SystemUtils.IS_OS_WINDOWS

0
投票

类似 UNIX 的解决方案是简单地尝试使用

--version
标志运行程序(在 Windows 上可能是
/?
或 - 就像在 7zip 情况下 - 根本没有任何标志)并检查它是否失败,或者什么返回代码将是。

类似:

public boolean is7zipInstalled() {
    try {
            Process process = Runtime.getRuntime().exec("7zip.exe");
            int code = process.waitFor();
            return code == 0;
    } catch (Exception e) {
            return false;
    }
}

0
投票

我知道这是一个相当老的问题,但如果有人仍然想要 Windows 的答案,我更喜欢使用命令行而不是已弃用的旧库

Powershell 中的示例:

(gp HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\*).DisplayName -Contains "Android Studio"

您将得到

True
False
作为输出

这仅适用于Windows


-1
投票

我假设您正在谈论 Windows。由于 Java 旨在成为一种独立于平台的语言,并且确定它的方式因平台而异,因此没有标准的 Java API 来检查这一点。不过,您可以借助对 DLL 进行 JNI 调用(该 DLL 会抓取 Windows 注册表)的帮助来完成此操作。然后,您可以检查与该软件关联的注册表项是否存在于注册表中。您可以使用第 3 方 Java API 抓取 Windows 注册表:jRegistryKey。

这是在 jRegistryKey 的帮助下的 SSCCE:

package com.stackoverflow.q2439984;

import java.io.File;
import java.util.Iterator;

import ca.beq.util.win32.registry.RegistryKey;
import ca.beq.util.win32.registry.RootKey;

public class Test {

    public static void main(String... args) throws Exception {
        RegistryKey.initialize(Test.class.getResource("jRegistryKey.dll").getFile());
        RegistryKey key = new RegistryKey(RootKey.HKLM, "Software\\Mozilla");
        for (Iterator<RegistryKey> subkeys = key.subkeys(); subkeys.hasNext();) {
            RegistryKey subkey = subkeys.next();
            System.out.println(subkey.getName()); // You need to check here if there's anything which matches "Mozilla FireFox".
        }
    }

}

但是,如果您打算拥有一个独立于平台的应用程序,那么您还必须考虑 Linux/UNIX/Mac/Solaris/等。 (换句话说:任何Java能够运行的地方)检测是否安装了FF的方法。否则,您必须将其作为仅限 Windows 的应用程序进行分发,并在

System#exit()
不是 Windows 时执行
System.getProperty("os.name")
并发出警告。

抱歉,我不知道如何在其他平台上检测是否安装了 FF,所以不要指望我会回答这个问题;)

© www.soinside.com 2019 - 2024. All rights reserved.