Java에서 운영체제를 프로그래밍 방식으로 판별하려면 어떻게 해야 하나요?
Java 프로그램이 프로그래밍 방식으로 실행되고 있는 호스트의 운영 체제를 확인하고 싶습니다(예:Windows 플랫폼인지 Unix 플랫폼인지에 따라 다른 속성을 로드할 수 있으면 좋겠습니다).100%의 신뢰성으로 이 작업을 수행하는 가장 안전한 방법은 무엇입니까?
다음을 사용할 수 있습니다.
System.getProperty("os.name")
추신. 이 코드가 유용할 수 있습니다.
class ShowProperties {
public static void main(String[] args) {
System.getProperties().list(System.out);
}
}
Java 구현에 의해 제공되는 모든 속성을 인쇄하기만 하면 됩니다.속성을 통해 Java 환경에 대해 무엇을 찾을 수 있는지 알 수 있습니다. :- )
다른 답변에서 알 수 있듯이 System.getProperty는 원시 데이터를 제공합니다.그러나 Apache Commons Lang 구성 요소는 java.lang에 대한 래퍼를 제공합니다.앞서 말한 Swingx OS 유틸리티와 같은 편리한 속성을 가진 시스템입니다.
2008년 10월:
정적 변수에 캐시하는 것이 좋습니다.
public static final class OsUtils
{
private static String OS = null;
public static String getOsName()
{
if(OS == null) { OS = System.getProperty("os.name"); }
return OS;
}
public static boolean isWindows()
{
return getOsName().startsWith("Windows");
}
public static boolean isUnix() // and so on
}
이렇게 하면 OS를 요청할 때마다 애플리케이션 수명 동안 속성을 두 번 이상 가져오지 않습니다.
2016년 2월: 7년 이상 후:
Windows 10 에는 버그가 있습니다(원래의 회답시에는 없었습니다).
Windows 10 용 "Java의 "os.name"을 참조하십시오.
위 답변의 일부 링크가 끊어진 것 같습니다.아래 코드에 현재 소스 코드에 포인터를 추가하고 결과를 평가할 때 스위치 문을 사용할 수 있도록 Enum을 답변으로 사용하여 체크를 처리하는 방법을 제공합니다.
OsCheck.OSType ostype=OsCheck.getOperatingSystemType();
switch (ostype) {
case Windows: break;
case MacOS: break;
case Linux: break;
case Other: break;
}
도우미 클래스는 다음과 같습니다.
/**
* helper class to check the operating system this Java VM runs in
*
* please keep the notes below as a pseudo-license
*
* http://stackoverflow.com/questions/228477/how-do-i-programmatically-determine-operating-system-in-java
* compare to http://svn.terracotta.org/svn/tc/dso/tags/2.6.4/code/base/common/src/com/tc/util/runtime/Os.java
* http://www.docjar.com/html/api/org/apache/commons/lang/SystemUtils.java.html
*/
import java.util.Locale;
public static final class OsCheck {
/**
* types of Operating Systems
*/
public enum OSType {
Windows, MacOS, Linux, Other
};
// cached result of OS detection
protected static OSType detectedOS;
/**
* detect the operating system from the os.name System property and cache
* the result
*
* @returns - the operating system detected
*/
public static OSType getOperatingSystemType() {
if (detectedOS == null) {
String OS = System.getProperty("os.name", "generic").toLowerCase(Locale.ENGLISH);
if ((OS.indexOf("mac") >= 0) || (OS.indexOf("darwin") >= 0)) {
detectedOS = OSType.MacOS;
} else if (OS.indexOf("win") >= 0) {
detectedOS = OSType.Windows;
} else if (OS.indexOf("nux") >= 0) {
detectedOS = OSType.Linux;
} else {
detectedOS = OSType.Other;
}
}
return detectedOS;
}
}
다음 JavaFX 클래스에는 현재 OS(isWindows(), isLinux()...)를 판별하는 정적 메서드가 있습니다.
- com.sun.comafx.플랫폼유틸
- com.sun.media 를 선택합니다.jfxmediaimpl 입니다.호스트 유틸리티
- com.sun.sunafx.discl을 클릭합니다.유틸리티
예제:
if (PlatformUtil.isWindows()){
...
}
TL;DR
에 하는 : OS の os os for for 。System.getProperty("os.name")
.
근데 잠깐만!!!
유틸리티 클래스를 만들어 재사용할 수 있습니다.또, 복수의 콜에서는, 한층 더 고속이 될 가능성이 있습니다.깨끗하게, 깨끗하게, 빨리!
이러한 유틸리티 함수의 Util 클래스를 만듭니다.그런 다음 각 운영 체제 유형에 대해 공용 에넘을 생성합니다.
public class Util {
public enum OS {
WINDOWS, LINUX, MAC, SOLARIS
};// Operating systems.
private static OS os = null;
public static OS getOS() {
if (os == null) {
String operSys = System.getProperty("os.name").toLowerCase();
if (operSys.contains("win")) {
os = OS.WINDOWS;
} else if (operSys.contains("nix") || operSys.contains("nux")
|| operSys.contains("aix")) {
os = OS.LINUX;
} else if (operSys.contains("mac")) {
os = OS.MAC;
} else if (operSys.contains("sunos")) {
os = OS.SOLARIS;
}
}
return os;
}
}
이제 다음과 같이 모든 클래스의 클래스를 쉽게 호출할 수 있습니다(P.S. os variable을 static으로 선언했기 때문에 시스템 유형을 식별하는 데 시간이 한 번만 소요되며 애플리케이션이 정지될 때까지 사용할 수 있습니다.)
switch (Util.getOS()) {
case WINDOWS:
//do windows stuff
break;
case LINUX:
바로 그거야!
로는, 「중요한 것」이 있습니다.class
아래에 있는 것과 유사합니다.
import java.util.Locale;
public class OperatingSystem
{
private static String OS = System.getProperty("os.name", "unknown").toLowerCase(Locale.ROOT);
public static boolean isWindows()
{
return OS.contains("win");
}
public static boolean isMac()
{
return OS.contains("mac");
}
public static boolean isUnix()
{
return OS.contains("nux");
}
}
이 특정 실장은 매우 신뢰성이 높으며 보편적으로 적용할 수 있어야 합니다..class
선택할 수 있습니다.
이거 먹어봐, 간단하고 쉽게
System.getProperty("os.name");
System.getProperty("os.version");
System.getProperty("os.arch");
오픈 소스 프로젝트가 이러한 작업을 수행하는 방법에 관심이 있는 경우, 이 잡동사니를 다루는 Teracotta 클래스(Os.java)를 확인해 보십시오.
-
http://svn.terracotta.org/svn/tc/dso/trunk/code/base/common/src/com/tc/util/runtime/ - http://svn.terracotta.org/svn/tc/dso/tags/2.6.4/code/base/common/src/com/tc/util/runtime/
JVM 버전(Vm.java 및 VmVersion.java)을 처리하는 것과 유사한 클래스를 다음 사이트에서 볼 수 있습니다.
아래 코드는 시스템 API에서 얻을 수 있는 값, 이 API를 통해 얻을 수 있는 모든 값을 나타냅니다.
public class App {
public static void main( String[] args ) {
//Operating system name
System.out.println(System.getProperty("os.name"));
//Operating system version
System.out.println(System.getProperty("os.version"));
//Path separator character used in java.class.path
System.out.println(System.getProperty("path.separator"));
//User working directory
System.out.println(System.getProperty("user.dir"));
//User home directory
System.out.println(System.getProperty("user.home"));
//User account name
System.out.println(System.getProperty("user.name"));
//Operating system architecture
System.out.println(System.getProperty("os.arch"));
//Sequence used by operating system to separate lines in text files
System.out.println(System.getProperty("line.separator"));
System.out.println(System.getProperty("java.version")); //JRE version number
System.out.println(System.getProperty("java.vendor.url")); //JRE vendor URL
System.out.println(System.getProperty("java.vendor")); //JRE vendor name
System.out.println(System.getProperty("java.home")); //Installation directory for Java Runtime Environment (JRE)
System.out.println(System.getProperty("java.class.path"));
System.out.println(System.getProperty("file.separator"));
}
}
답변:-
Windows 7
6.1
;
C:\Users\user\Documents\workspace-eclipse\JavaExample
C:\Users\user
user
amd64
1.7.0_71
http://java.oracle.com/
Oracle Corporation
C:\Program Files\Java\jre7
C:\Users\user\Documents\workspace-Eclipse\JavaExample\target\classes
\
팔로잉은 더 적은 라인으로 더 넓은 커버리지를 제공할 수 있다고 생각합니다.
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 를 참조해 주세요.
보안에 민감한 환경에서 작업하는 경우 이 내용을 읽어보십시오.
System#getProperty(String)
서브루틴!사실, 다음을 포함한 거의 모든 재산들이os.arch
,os.name
, , , , 입니다.os.version
예상대로 읽기 전용이 아니라 정반대입니다.
「」, 「」의 를 가지는 입니다.System#setProperty(String, String)
할 수 .subroutine은 반환된 리터럴을 변경할 수 있습니다.꼭 이 '아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아.이 문제는 이른바SecurityManager
자세한 내용은 이쪽에서 설명하겠습니다.
는 모든 이할 수 입니다.JAR
되고 있는 (을 통해)-Dos.name=
,-Dos.arch=
으로는 「 」를 하는 방법이 있습니다.RuntimeMXBean
여기 보이는 것처럼요.다음 코드 스니펫을 통해 이를 실현하는 방법에 대한 정보를 얻을 수 있습니다.
RuntimeMXBean runtimeMxBean = ManagementFactory.getRuntimeMXBean();
List<String> arguments = runtimeMxBean.getInputArguments();
for (String argument : arguments) {
if (argument.startsWith("-Dos.name") {
// System.getProperty("os.name") altered
} else if (argument.startsWith("-Dos.arch") {
// System.getProperty("os.arch") altered
}
}
Swingx의 OS Utils가 그 일을 하고 있는 것을 알 수 있습니다.
String osName = System.getProperty("os.name");
System.out.println("Operating system " + osName);
난 볼프강의 답변이 마음에 들었어. 왜냐하면 난 그런 것들이 항상 있어야 한다고 믿으니까...
그래서 제가 좀 바꿔서 공유하려고 합니다:)
/**
* types of Operating Systems
*
* please keep the note below as a pseudo-license
*
* helper class to check the operating system this Java VM runs in
* http://stackoverflow.com/questions/228477/how-do-i-programmatically-determine-operating-system-in-java
* compare to http://svn.terracotta.org/svn/tc/dso/tags/2.6.4/code/base/common/src/com/tc/util/runtime/Os.java
* http://www.docjar.com/html/api/org/apache/commons/lang/SystemUtils.java.html
*/
public enum OSType {
MacOS("mac", "darwin"),
Windows("win"),
Linux("nux"),
Other("generic");
private static OSType detectedOS;
private final String[] keys;
private OSType(String... keys) {
this.keys = keys;
}
private boolean match(String osKey) {
for (int i = 0; i < keys.length; i++) {
if (osKey.indexOf(keys[i]) != -1)
return true;
}
return false;
}
public static OSType getOS_Type() {
if (detectedOS == null)
detectedOS = getOperatingSystemType(System.getProperty("os.name", Other.keys[0]).toLowerCase());
return detectedOS;
}
private static OSType getOperatingSystemType(String osKey) {
for (OSType osType : values()) {
if (osType.match(osKey))
return osType;
}
return Other;
}
}
그냥 sun.awt로 하면 돼요.OSInfo #취득OSType() 메서드
상위 답변의 약간 짧고 깔끔한(그리고 열심히 계산된) 버전:
switch(OSType.DETECTED){
...
}
도우미 열거:
public enum OSType {
Windows, MacOS, Linux, Other;
public static final OSType DETECTED;
static{
String OS = System.getProperty("os.name", "generic").toLowerCase(Locale.ENGLISH);
if ((OS.contains("mac")) || (OS.contains("darwin"))) {
DETECTED = OSType.MacOS;
} else if (OS.contains("win")) {
DETECTED = OSType.Windows;
} else if (OS.contains("nux")) {
DETECTED = OSType.Linux;
} else {
DETECTED = OSType.Other;
}
}
}
시스템 OS 유형, 이름, 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));
}
}
com.sun.jna에서.다음과 같은 유용한 정적 메서드를 찾을 수 있습니다.
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>
그렇지 않으면 jen 라이브러리 jar 파일(예: jen-5.2.0.jar)을 찾아서 classpath에 추가합니다.
구글은 이 페이지를 "kotlin os name"으로 가리키고 있으므로 @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
}
그냥 사용하다com.sun.javafx.util.Utils
이하와 같습니다.
if ( Utils.isWindows()){
// LOGIC HERE
}
또는 사용
boolean isWindows = OSInfo.getOSType().equals(OSInfo.OSType.WINDOWS);
if (isWindows){
// YOUR LOGIC HERE
}
언급URL : https://stackoverflow.com/questions/228477/how-do-i-programmatically-determine-operating-system-in-java
'itsource' 카테고리의 다른 글
어떻게 하면 C 프리프로세서와 두 번 연결하여 "arg ##_# MACRO"처럼 매크로를 확장할 수 있습니까? (0) | 2022.07.21 |
---|---|
Java에서 String에서 파일 확장자를 자르는 방법은 무엇입니까? (0) | 2022.07.21 |
Vue.js - 개체를 다른 데이터 속성에 '복사'할 때 바인딩하지 않음 (0) | 2022.07.21 |
16진수를 C로 표시하는 방법 (0) | 2022.07.17 |
localDate to java.util.날짜 및 그 반대도 단순 변환입니까? (0) | 2022.07.17 |