gpt4 book ai didi

java - 从 Java 获取 Linux Distro

转载 作者:搜寻专家 更新时间:2023-10-31 19:40:02 31 4
gpt4 key购买 nike

从 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/

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