java move函数重新调用,从Java调用Windows内核函数的最简单方法是什么?

While searching for how to do this, I found some vague discussion about different options, like JNI vs JNA, but not much in the way of concrete examples.

Context: if Java's File.renameTo() cannot do it's job (for whatever reason; it is a little problematic), I'd like to fall back to directly using this native Windows function, which is defined in kernel32.dll (from this answer):

BOOL WINAPI MoveFile(

__in LPCTSTR lpExistingFileName,

__in LPCTSTR lpNewFileName

);

So, using whatever approach, how exactly would you call that function from within Java code? I'm looking for the simplest way, with the minimum amount of non-Java code or extra steps (e.g. in compilation or deployment).

解决方案

If you go with JNA, consider invoking MoveFileW directly - it saves having to provide configuration info to choose between Unicode and ANSI calls.

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());

}

}

}

EDIT: I've edited my answer after checking the code - I was mistaken about using char[] in the signature - it is better to use WString.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值