Java에서 Windows 커널 기능을 호출하는 가장 쉬운 방법은 무엇입니까?
-
05-07-2019 - |
문제
이 작업을 수행하는 방법을 검색하는 동안 JNI vs JNA와 같은 다양한 옵션에 대한 모호한 토론을 찾았지만 콘크리트 예제는 그리 많지 않았습니다.
맥락 : Java라면 File.renameTo()
일을 할 수 없습니다 (어떤 이유로 든; 약간 문제가 있습니다), Kernel32.dll (kernel32.dll)에 정의 된이 기본 Windows 함수를 직접 사용하고 싶습니다.이 답변에서):
BOOL WINAPI MoveFile(
__in LPCTSTR lpExistingFileName,
__in LPCTSTR lpNewFileName
);
따라서 어떤 접근법을 사용하여 Java 코드 내에서 해당 기능을 정확히 어떻게 호출합니까? 최소 금액의 비 Java 코드 또는 추가 단계 (예 : 컴파일 또는 배포에서)로 가장 간단한 방법을 찾고 있습니다.
해결책
JNA와 함께 가면 호출을 고려하십시오 MoveFilew 직접 - 유니 코드와 ANSI 호출 중에서 선택할 수 있도록 구성 정보를 제공 해야하는 것을 저장합니다.
import java.io.*;
import com.sun.jna.*;
public class Ren {
static interface Kernel32 extends Library {
public static Kernel32 INSTANCE = (Kernel32) Native
.loadLibrary("Kernel32", Kernel32.class);
public static int FORMAT_MESSAGE_FROM_SYSTEM = 4096;
public static int FORMAT_MESSAGE_IGNORE_INSERTS = 512;
public boolean MoveFileW(WString lpExistingFileName,
WString lpNewFileName);
public int GetLastError();
public int FormatMessageW(int dwFlags,
Pointer lpSource, int dwMessageId,
int dwLanguageId, char[] lpBuffer, int nSize,
Pointer Arguments);
}
public static String getLastError() {
int dwMessageId = Kernel32.INSTANCE.GetLastError();
char[] lpBuffer = new char[1024];
int lenW = Kernel32.INSTANCE.FormatMessageW(
Kernel32.FORMAT_MESSAGE_FROM_SYSTEM
| Kernel32.FORMAT_MESSAGE_IGNORE_INSERTS, null,
dwMessageId, 0, lpBuffer, lpBuffer.length, null);
return new String(lpBuffer, 0, lenW);
}
public static void main(String[] args) throws IOException {
String from = ".\\from.txt";
String to = ".\\to.txt";
new FileOutputStream(from).close();
if (!Kernel32.INSTANCE.MoveFileW(new WString(from),
new WString(to))) {
throw new IOException(getLastError());
}
}
}
편집 : 코드를 확인한 후 답변을 편집했습니다. 서명에서 char []를 사용하는 것에 대해 착각했습니다. 사용하는 것이 좋습니다. WSTRING.
다른 팁
이것이 정말로 필요한 경우 (Renameto가 작동하지 않으며 MoveFile이 될 것입니다) JNA. 대부분의 작업이 이미 com.mucommander.file.util에서 수행 된 것 같습니다.kernel32.java/kernel32api.java.
를 기반으로 Nativecall 라이브러리 나는 다음을했다 POC 응용 프로그램.
사용합니다 MoveFileA
기능 kernel32.dll
런. 바트와 모든 항아리와 DLL이있는 완전한 작업 샘플로 제공됩니다.
포함 된 test.txt를 test2.txt로 이동합니다
NativeCall Library 버전이 마음에 들지 않으면 다른 작업을 수행했습니다. POC 응용 프로그램 /resing을 기반으로합니다 Java Native Access (JNA) 도서관. 이 시간 MoveFileA
그리고 MoveFileW
구현되고 시연됩니다.