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