CodeMonkey流水账:Java取得Linux发行版名称

CodeMonkey流水账:Java取得Linux发行版名称,第1张

CodeMonkey流水账:Java取得Linux发行版名称

文章目录
  • 1)System.getProperty("os.name")在Linux下的问题
  • 2)Linux下用os-release获取发行版友好名称

1)System.getProperty(“os.name”)在Linux下的问题

问题就是只能显示“Linux”,而没有具体的发行版名称。
其实不能算问题,但是很不方便啊,比如我之前的代码:

MyLog(TNU.LogType.INFO,"运行环境: "+System.getProperty("os.name")
		+" "+System.getProperty("os.arch")
		+" "+System.getProperty("os.version")
		+" "+System.getProperty("java.vm.name")
		+" "+System.getProperty("java.version")
		+" Hadoop " +org.apache.hadoop.util.VersionInfo.getVersion()

Win10下算正常,PS:目前Win11依然会显示Win10:

运行环境: Windows 10 amd64 10.0 OpenJDK 64-Bit Server VM 1.8.0_312 Hadoop 3.3.1

到了WSL下就看不懂了,到底用的ubuntu还是CentOS???

运行环境: Linux amd64 5.10.60.1-microsoft-standard-WSL2 OpenJDK 64-Bit Server VM 1.8.0_292 Hadoop 3.3.1

2)Linux下用os-release获取发行版友好名称

所以只好改一下代码,发现是Linux则取“/etc/os-release”来判断。
如果不是Linux还是返回System.getProperty(“os.name”)原本的内容。
感谢Linux一切皆文件:

MyLog(TNU.LogType.INFO,"运行环境: "+getOsName()
		+" "+System.getProperty("os.arch")
		+" "+System.getProperty("os.version")
		+" "+System.getProperty("java.vm.name")
		+" "+System.getProperty("java.version")
		+" Hadoop " +org.apache.hadoop.util.VersionInfo.getVersion()
......
	public static String getOsName() throws Exception {
		String aName=System.getProperty("os.name");
		final String aTag ="PRETTY_NAME=";
		if (aName.equalsIgnoreCase("Linux")) {
			File osRelease = new File("/etc/os-release");
			if (osRelease.exists()) {
				try (
						BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(osRelease)))
				) {
					String aline;
					while ((aline = br.readLine()) != null) {
						if (aline.startsWith(aTag)) {
							aName = aline.substring(aTag.length());
							aName = aName.replace(""", "");
							break;
						}
					}
				}
			}
		}
		return aName;
	}

WSL的ubuntu下显示:

运行环境: Ubuntu 20.04.3 LTS amd64 5.10.60.1-microsoft-standard-WSL2 OpenJDK 64-Bit Server VM 1.8.0_292 Hadoop 3.3.1

虚拟机下的CentOS显示:

运行环境: CentOS Linux 7 (Core) amd64 3.10.0-1160.49.1.el7.x86_64 OpenJDK 64-Bit Server VM 1.8.0_312 Hadoop 3.3.1

OK,问题解决。

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/zaji/5679184.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-17
下一篇 2022-12-17

发表评论

登录后才能评论

评论列表(0条)

保存