java - 从 Java 获取 Linux Distro

标签 java operating-system linux-distro

从 java 中,我得到了我正在工作的操作系统的名称。看下面的代码:

System.out.println(System.getProperty("os.name"));

在 windows xp 中,打印如下:Windows XP

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

任何人都可以帮助我使用 java 代码找到我正在使用的 linux 版本(如 ubuntu 或 fedora)吗?是否可以从 java 中找到 linux 发行版?

最佳答案

此代码可以帮助您:

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();
}

更新

如果你只需要版本,试试 uname -a

更新

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

//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());
    }
}

关于java - 从 Java 获取 Linux Distro,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15018474/

相关文章:

linux - 为什么 "swappiness"的讨论就像一次只能在一个地方的信息一样?

内置 ffmpeg 库的 Linux 发行版

java - 为什么jvm生成serialVersionUID?

java - 使 GWT 可爬行

java - 将 Java 7 升级到 Java 8 - Java 8 字符串开关是否已弃用?

python - 如何剥离 Python 输出

linux - 为 Linux 发行版做贡献

javascript - 在 onchange 事件时在 div 标签中显示 Map 值

创建僵尸进程

assembly - 目标代码与机器代码