windows下自动生成文件夹下所有JNI所需的.h头文件

本文介绍了一个Java程序如何将.class文件转换为.h文件,用于JNI集成,并提供了一个自动清理无用代码的流程。通过使用javah命令和Java程序实现,可以自动为类生成相应的.h文件,便于跨平台开发和调用。同时,通过筛选和删除不必要的.h文件,确保代码精简高效。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

[size=x-large][color=red][b]以下程序打包成jar后在生成的.class文件的根路径(如elcipse工程的bin文件夹)下运行即可!![/b][/color][/size]
生成的.h文件放在当前目录的h文件夹下
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;

public class GenerateHFile {
static String suffix = ".class";
static String outputFolder = ".\\h\\";//输出文件夹

/**生成以classRoot为根文件夹的类的JNI用的.h文件,其中folder为当前路径,他应为classRoot的一个子路径
* @param folder 当前文件夹
* @param classRoot 类文件的根路径
*/
static void generateHFile(File folder, File classRoot) {
File fs[] = folder.listFiles();
for (File file : fs) {
if (file.isDirectory()) {
generateHFile(file, classRoot);
} else if (file.getName().endsWith(suffix)) {
String exe = "javah";
String arg = classRoot.getAbsolutePath();
String tmp = file.getAbsolutePath();
tmp = tmp.substring(arg.length() + 1,
tmp.length() - suffix.length());
tmp = tmp.replace(File.separator.charAt(0), '.');
String cmds[] = { exe, "-d", outputFolder,"-classpath",arg, tmp };
try {
Process p = Runtime.getRuntime().exec(cmds);
p.waitFor();
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}

System.out.println(arg);
}
}
}

static String prefix = "JNIEXPORT";

/**
* 清除不包含native方法的h文件,根据文件中是否含有"JNIEXPORT"来进行判断
*/
static void clean() {
File[] fs = new File(outputFolder).listFiles();
Label: for (int i = 0; i < fs.length; i++) {

try {
BufferedReader br = new BufferedReader(new FileReader(fs[i]));

while (br.ready()) {
String s = br.readLine();
if (s.startsWith(prefix)) {
continue Label;
}
}
br.close();
System.out.print("has deleted successfully: " + fs[i]);
boolean b = fs[i].delete();
System.out.println(" : " + b);

} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}

public static void main(String[] args) {
File dir = new File(".");
new File(outputFolder).mkdirs();
generateHFile(dir, dir);
clean();

}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值