Java 언어에서 레지스트리 생성, 삽입, 삭제, 수정 방법Java 언어에서 레지스트리 생성, 삽입, 삭제, 수정 방법

Posted at 2011. 5. 13. 17:19 | Posted in 카테고리 없음
import com.sun.jna.platform.win32.Advapi32Util;
import com.sun.jna.platform.win32.WinReg;

public class Test {
	private static String regPath;
	private static String regName;
	private static String regValue;
	
	Test() {
		regPath = null;
		regName = null;
		regValue = null;
	}
	
	public static void main(String args[]) {
		// 경로, 이름, 데이터 변수 초기화
		regPath = "Software\\Microsoft\\Windows\\CurrentVersion\\Run";
		regName = "MyProgram";
		regValue = "\"C:\\Program Files\\SetReg\\SetReg.jar\" /autorun";
		
		// 시스템 사용자 이름 출력
		System.out.println("Your Name is " + Advapi32Util.getUserName() + ".");

		// 레지스트리 키 생성
		Advapi32Util.registryCreateKey(WinReg.HKEY_CURRENT_USER, regPath, regName);
		
		// 레지스트리 값 설정
		Advapi32Util.registrySetStringValue(WinReg.HKEY_CURRENT_USER, regPath, regName, regValue);
		
		// 레지스트리 값 읽기
		System.out.println(Advapi32Util.registryGetStringValue(WinReg.HKEY_CURRENT_USER, regPath, regName)); 
		
		// 레지스트리 값 삭제
		Advapi32Util.registryDeleteValue(WinReg.HKEY_CURRENT_USER, regPath, regName);
		
		// 레지스트리 키 삭제(값 삭제가 선행)
		Advapi32Util.registryDeleteKey(WinReg.HKEY_CURRENT_USER, regPath, regName); 
	}
}
다음은 Java 언어에서 레지스트리를 생성, 삽입, 삭제 그리고 수정하는 방법이다. 구글 검색을 통해 다양한 방법을 찾아보았지만 각자 나름의 장단점이 있었다. 그 중에서 가장 마음에 드는 것은 JNA(Java Native Access)를 사용하여 레지스트리를 접근하는 방법이다. Advapi32Util 클래스를 사용하여 레지스트리를 조작할 수 있다. Java에서 기본적으로 레지스트리를 조작하기 위해 제공해주는 클래스가 있지만 이 클래스는 레지스트리 트리의 Root 접근이 불가능하다. 아마도 보안 문제이기 때문에 그러한 것이라 생각한다.
//

Java Native AccessJava Native Access

Posted at 2011. 5. 13. 16:57 | Posted in 카테고리 없음

Java Native Access provides Java programs easy access to native shared libraries without using the Java Native Interface. JNA's design aims to provide native access in a natural way with a minimum of effort. No boilerplate or generated glue code is required.

현재 JNA 최신 버전은 3.2.7 인데 최근에 3.2.8로 업데이트 되었다. 이것이 필요하게 된 이유는 JAVA를 이용하여 윈도우 프로그래밍을 할 경우 한계점이 발생하기 때문이다. 예를 들어 레지스트리를 제어(생성, 삽입, 삭제, 수정)하기 위해서는 JNA가 필요하다.

import com.sun.jna.Library;
import com.sun.jna.Native;
import com.sun.jna.Platform;
 
/** Simple example of native library declaration and usage. */
public class HelloWorld {
    public interface CLibrary extends Library {
        CLibrary INSTANCE = (CLibrary) Native.loadLibrary(
            (Platform.isWindows() ? "msvcrt" : "c"), CLibrary.class);
        void printf(String format, Object... args);
    }
 
    public static void main(String[] args) {
        CLibrary.INSTANCE.printf("Hello, World\n");
        for (int i = 0; i < args.length; i++) {
            CLibrary.INSTANCE.printf("Argument %d: %s\n", i, args[i]);
        }
    }
}

위의 예제는 위키디피아에서 Java에서 printf 함수를 사용하여 "Hello, World"를 출력하는 소스 코드이다. 이것을 실행하기 위해서는 jna.jar 파일과 platform.jar 파일을 외부 라이브러리로 등록해 주어야 한다.

//