Java/Tip & Tech2009. 12. 11. 14:08

1편에 이어서 계속되는 Java로 Windows Registry 정보 가져오기입니다.

2009/12/11 - [Java/Tip & Tech] - [Java]Java로 Windows Registry 정보를 가져오기...1편


java.util.prefs.Prefrences 클래스로는 일단 아무 것도 못해 잡수시겠다는 판단을 내리고

다른 방법을 찾던 중 Windows의 "reg query" 명령어를 이용한 방법을 알게되었습니다.

간단하게 설명하자면 Windows의 "reg query"명령어를 실행한 다음에

그 결과를 InputStream으로 받아서 필요한 내용을 끄집어 내는 방법입니다.

먼저 "regedit" 명령어로 레지스트리 편집창을 열어서 (범행???)대상을 골랐습니다.



OK... 그러다가 현재 설치된 알집의 버전 정보를 가지고 와보기로 하였습니다.

Node : HKEY_CURRENT_USER\Software\ESTsoft\ALZip
Key : Version
Value : 7.52


인터넷에서 봤었던 예제 소스에서 필요한 것만 빼고 바꿀껀 싹 빠꿔서 아래와 같은 예제 소스가 나왔습니다.


01.import java.io.BufferedInputStream;
02.import java.io.IOException;
03. 
04.public class TestGetRegInfoByRegQuery {
05.    private static final String CMD_REG_QUERY = "reg query ";
06.    private static final String TOKEN_REGSTR = "REG_SZ";
07.    private static final String TOKEN_REGDWORD = "REG_DWORD";
08. 
09.    public static String getRegistryValue(String node, String key) {
10.        BufferedInputStream in = null;
11.        String regData = null;
12. 
13.        try {
14.            String strCmd = CMD_REG_QUERY + "\"" + node + "\" /v " + key;
15.            //System.out.println(strCmd);
16.             
17.            Process process = Runtime.getRuntime().exec(strCmd);
18.            in = new BufferedInputStream(process.getInputStream());
19.             
20.            // Data가 들어오는 동안 0.2초정도 대기
21.            try {
22.                Thread.sleep(200);
23.            } catch (InterruptedException ie) {
24.                ie.printStackTrace();
25.            }
26. 
27.            byte[] buff = new byte[in.available()];
28.            in.read(buff);
29.             
30.            regData = new String(buff);
31.        } catch (IOException ioe) {
32.            ioe.printStackTrace();
33.        } finally {
34.            try { in.close(); } catch (IOException ioe) {}
35.        }
36. 
37.        int index = regData.indexOf(TOKEN_REGSTR);
38.        if (index < 0)
39.            return null;
40. 
41.        return regData.substring(index + TOKEN_REGSTR.length()).trim();
42.    }
43. 
44.    public static void main(String[] args) {
45.        System.out.println(getRegistryValue("HKEY_CURRENT_USER\\Software\\ESTsoft\\ALZip", "Version"));
46.    }
47.}



실행한 결과는 아래와 같이 나오는군요.

7.52


사실 Runtime.getRuntime().exec(String command); 메소드를 이용하는 방법이라

그다지 기분이 좋지 않고, 찜찜한 구석이 있기는 하지만

일단 과정보다도 쪼금 더 중요한 결과가 잘 나오는지라 이 방법을 사용하기로 하였습니다.

아마도 조만간 Windows의 "reg query" 명령어의 옵션을 정리해서 올리고 있을 것 같네요~~^^;

Posted by Huikyun