从Java获取Linux Distro

Has*_*ena 5 java operating-system linux-distro

从Java,我得到了操作系统Iam的名称。参见下面的代码:

System.out.println(System.getProperty("os.name"));
Run Code Online (Sandbox Code Playgroud)

在Windows XP中,它显示为: Windows XP

但是在ubuntu / fedora中,它仅显示Linux

谁能帮助我使用Java代码找到Iam使用的Linux版本(例如ubuntu或fedora)?是否可以从Java找到Linux发行版?

Pbx*_*Man 5

此代码可以帮助您:

String[] cmd = {
"/bin/sh", "-c", "cat /etc/*-release" };

try {
    Process p = Runtime.getRuntime().exec(cmd);
    BufferedReader bri = new BufferedReader(new InputStreamReader(
            p.getInputStream()));

    String line = "";
    while ((line = bri.readLine()) != null) {
        System.out.println(line);
    }
} catch (IOException e) {

    e.printStackTrace();
}
Run Code Online (Sandbox Code Playgroud)

更新

如果您只需要版本,请尝试使用 uname -a

更新

一些 linux 发行版在 /proc/version 文件中包含发行版。这是一个在不调用任何 SO 命令的情况下从 java 打印它们的示例

//lists all the files ending with -release in the etc folder
File dir = new File("/etc/");
File fileList[] = new File[0];
if(dir.exists()){
    fileList =  dir.listFiles(new FilenameFilter() {
        public boolean accept(File dir, String filename) {
            return filename.endsWith("-release");
        }
    });
}
//looks for the version file (not all linux distros)
File fileVersion = new File("/proc/version");
if(fileVersion.exists()){
    fileList = Arrays.copyOf(fileList,fileList.length+1);
    fileList[fileList.length-1] = fileVersion;
}       
//prints all the version-related files
for (File f : fileList) {
    try {
        BufferedReader myReader = new BufferedReader(new FileReader(f));
        String strLine = null;
        while ((strLine = myReader.readLine()) != null) {
            System.out.println(strLine);
        }
        myReader.close();
    } catch (Exception e) {
        System.err.println("Error: " + e.getMessage());
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 这只是一个方便的问题。您必须列出并阅读所有 *-release 文件。 (3认同)
  • 为什么需要运行“Process”来读取文件?为什么不直接在 Java 中打开文件? (2认同)

小智 5

从这里开始,我扩展了代码以包含不同的回退方案,以便在多个平台上获得操作系统版本。

  • Windows 具有足够的描述性,您可以从“os.name”系统属性中获取信息
  • Mac OS :您需要根据版本保留一份发布名称列表
  • Linux :这是最复杂的,这里是后备列表:
    - 如果发行版符合 LSB,则从 LSB 发布文件中
    获取信息 - 从 /etc/system-release
    获取信息(如果存在)- 从在 /etc/ 中以 '-release' 结尾的任何文件
    - 从/etc/ 中以 '_version' 结尾的任何文件中获取信息(主要用于 Debian)
    - 从 /etc/issue 中获取信息(如果存在)
    - 最坏的情况,获取/proc/version 中的哪些信息可用

  • 您可以在此处获取实用程序类:https :
    //github.com/aurbroszniowski/os-platform-finder