我想确定我的Java程序以编程方式运行的主机的操作系统(例如:我希望能够根据我是在Windows还是Unix平台上加载不同的属性)。100%可靠的最安全的方法是什么?
当前回答
因为谷歌点“kotlin os名称”到这个页面,这里是@Memin的答案的kotlin版本:
private var _osType: OsTypes? = null
val osType: OsTypes
get() {
if (_osType == null) {
_osType = with(System.getProperty("os.name").lowercase(Locale.getDefault())) {
if (contains("win"))
OsTypes.WINDOWS
else if (listOf("nix", "nux", "aix").any { contains(it) })
OsTypes.LINUX
else if (contains("mac"))
OsTypes.MAC
else if (contains("sunos"))
OsTypes.SOLARIS
else
OsTypes.OTHER
}
}
return _osType!!
}
enum class OsTypes {
WINDOWS, LINUX, MAC, SOLARIS, OTHER
}
其他回答
此代码用于显示有关系统操作系统类型、名称、java信息等的所有信息。
public static void main(String[] args) {
// TODO Auto-generated method stub
Properties pro = System.getProperties();
for(Object obj : pro.keySet()){
System.out.println(" System "+(String)obj+" : "+System.getProperty((String)obj));
}
}
试试这个,简单易行
System.getProperty("os.name");
System.getProperty("os.version");
System.getProperty("os.arch");
获取操作系统名称,只需使用:
Platform.getOS()
假设你想看看平台是否是linux:
if (Platform.getOS().equals(Platform.OS_LINUX)) {
}
类似地,Platform类为其他操作系统名称定义了常量。平台类是org.eclipse.core.runtime包的一部分。
我认为下面的内容可以用更少的字里行间覆盖更广的范围
import org.apache.commons.exec.OS;
if (OS.isFamilyWindows()){
//load some property
}
else if (OS.isFamilyUnix()){
//load some other property
}
更多详情请访问:https://commons.apache.org/proper/commons-exec/apidocs/org/apache/commons/exec/OS.html
在com.sun.jna.Platform类中,您可以找到有用的静态方法,例如
Platform.isWindows();
Platform.is64Bit();
Platform.isIntel();
Platform.isARM();
还有更多。
如果使用Maven,只需添加依赖项
<dependency>
<groupId>net.java.dev.jna</groupId>
<artifactId>jna</artifactId>
<version>5.2.0</version>
</dependency>
否则,只需找到jna库jar文件(例如jna-5.2.0.jar)并将其添加到类路径。
推荐文章
- Intellij IDEA Java类在保存时不能自动编译
- 何时使用Mockito.verify()?
- 在maven中安装mvn到底做什么
- 不可变与不可修改的集合
- 如何在JSON中使用杰克逊更改字段名
- GSON -日期格式
- 如何从线程捕获异常
- 无法解析主机"<URL here>"没有与主机名关联的地址
- 如何在Java中打印二叉树图?
- String.format()在Java中格式化双重格式
- com.jcraft.jsch.JSchException: UnknownHostKey
- Java中的操作符重载
- 如何加速gwt编译器?
- 在Hibernate中重新连接分离对象的正确方法是什么?
- 应该……接住环内还是环外?