メインコンテンツまでスキップ

시스템

의외로? 도움이 많이 될것도 같은 시스템 쪽이다
레퍼런스 코드를 쭈욱 쳐보면서 느낌을 잡아보자

시스템 정보를 취득

public class GetSystemProperty {

public static void main(String[] args) {
System.out.println(
"언어 : " + System.getProperty("user.language")
);
System.out.println(
"국가 : " + System.getProperty("user.country")
);
System.out.println(
"자바버전 : " + System.getProperty("java.version")
);
System.out.println(
"OS이름 : " + System.getProperty("os.name")
);
}
}

언어 : ko
국가 : KR
자바버전 : 17
OS이름 : Linux

getProperty 쪽에 들어가면 시스템프로퍼티로 알아볼수 있는것들이 엄청 많다!

현재 디렉토리 / 유저 홈 디렉토리

public class GetSystemProperty {

public static void main(String[] args) {
System.out.println(
"현재 디렉토리 : " + System.getProperty("user.dir")
);
System.out.println(
"유저의 홈 디렉토 : " + System.getProperty("user.home")
);
}
}

현재 디렉토리 : /home/user/바탕화면/Maven-Quick-Start/practice
유저의 홈 디렉토 : /home/user

개행 문자를 취득

public class GetLineSeparator {

public static void main(String[] args) {

String str = System.getProperty("line.separator");
char[] chars = str.toCharArray();

System.out.println("개행 문자");

for(char ch : chars) {
System.out.println("0x" + Integer.toHexString(ch));
}
}
}
개행 문자
0xa

현재 시스템 프로퍼티를 출력

public class GetSystemProperty {

public static void main(String[] args) {

System.out.println(System.getProperty("param"));
}
}
null

자바 기동시에 -Dparam=값 을 넣어서 기동했을 경우에는 파라미터값이 나온다. 예제는 null이지만..

자바 프로그램 종료

정식으로 종료하는게 있었다니.. ㅋㅋ

public class SystemPractice {

public static void main(String[] args) {

System.out.println("start");

System.exit(0);

System.out.println("종료 후에 내가 나오면 안되지~ ");

}
}

start

그러하다. 종료후의 처리가 나오면 안되지

프로그램 종료시에 특정 처리를 하고 종료

public class SystemPractice {

public static void main(String[] args) throws InterruptedException {

System.out.println("start");

// 익명 클래스. 종료시의 처리를 설정
Runtime runtime = Runtime.getRuntime();
runtime.addShutdownHook(new Thread() {

// 종료시 실행할 내용
@Override
public synchronized void start() {
System.out.println("종료합니다");
}
});

// 2초 기다림
TimeUnit.SECONDS.sleep(2);

System.out.println("end");
}
}
start
end
종료합니다

종료시에 특정 처리를 하고싶으면.

  • 종료시의 처리를 정의한 Thread 클래스의 서브 클래스를 준비한다.
  • Runtime.addShutdownHook 메서드의 파라미터에 그 인스턴스를 설정한다

외부 프로그램을 기동

public class SystemPractice {

public static void main(String[] args) throws IOException {

// OS 의 이름을 취득
String osName = System.getProperty("os.name");

ProcessBuilder processBuilder;

if (osName.startsWith("Windows")) {
processBuilder = new ProcessBuilder("notepad.exe");
} else if (osName.startsWith("Mac")) {
processBuilder = new ProcessBuilder("open", "-a", "TextEdit");
} else {
processBuilder = new ProcessBuilder("code");
}

// 실행시의 디렉토리를 홈 디렉토리로 지정
File homeDir = new File(System.getProperty("user.home"));

processBuilder.start();
}
}

우아 !! 비쥬얼 스튜디오 코드가 자바로 실행된다 !! 짱이네
외부 프로그램을 기동하려고 한다면, 일단 ProcessBuilder 인스턴스를 작성한다
ProcessBuilder 생성자에 실행할 프로그램명과 옵션을 넘겨서 실행한다
ProcessBuilder.start 메서드에 의해서 실행한다
exec메서드도 실행을 하는메서드인데. 내부적으로는 start메서드를 부르고 있다

기동한 외부 프로그램의 표준입출력을 제어

public class SystemPractice {

public static void main(String[] args) throws IOException {

// OS 이름을 취득
String osName = System.getProperty("os.name");
String[] cmd = osName.startsWith("Windows")
? new String[] {"cmd.exe", "/c", "date", "/t"}
: new String[] {"date"};

// 현재날짜를 취득하는 커맨드를 실행
ProcessBuilder processBuilder = new ProcessBuilder(cmd);
Process process = processBuilder.start();

// 커맨드 실행결과가 표준출력이 될것이다
// 표준 출력된 내용을 읽어들이는 리더를 준비한다
BufferedReader reader = new BufferedReader(
new InputStreamReader(process.getInputStream())
);


// 표준출력된 내용을 그대로 콘솔에 출력한다
String line = null;
while (null != (line = reader.readLine())) {
System.out.println(line);
}
}
}
2022. 02. 02. (수) 08:11:26 JST

이 소스는 많은 공부가 되는 소스다 특히 표준입출력의 부분에서

환경변수 값을 출력

public class SystemPractice {

public static void main(String[] args) throws IOException {

System.out.println(
"호스트명 : " + System.getenv("HOSTNAME")
);

System.out.println(
"언어 : " + System.getenv("LANG")
);

System.out.println(
"쉘 : " + System.getenv("SHELL")
);
}
}
호스트명 : localhost.localdomain
언어 : ko_KR.UTF-8
쉘 : /bin/bash

리눅스에서 env 라고 치면 나오는 것들을 출력할 수 있다

JavaVM 메모리의 남은 용량을 취득

public class SystemPractice {

public static void main(String[] args) throws IOException {

Runtime runtime = Runtime.getRuntime();

long free = runtime.freeMemory();
long total = runtime.totalMemory();
long max = runtime.maxMemory();

System.out.println("여유 메모리 : " + free);
System.out.println("총 메모리 : " + total);
System.out.println("최대 메모리 : " + max);
}
}
여유 메모리 :  395974808
총 메모리 : 402653184
최대 메모리 : 6249512960

자바의 VM이 사용하는 메모리 영역은 크게 2가지로 나뉜다
스레드별로 할애해서 메서드안의 로컬변수 등을 넣는 스택
만든 인스턴스을 넣는 이다
Runtime.freeMemory메서드를 사용하면, 힙 영역의 남은 메모리 용량을 바이트 단위로 알 수 있다