使用Java从$ PATH获取可执行文件的绝对path

我在我的命令行Java应用程序中调用nodeJS可执行文件。 由于可执行文件位于$PATHvariables中的某个位置,因此可以简单地将其称为node 。 但是,我必须提供一个参数(要运行的.js文件),如果我提供了一个相对于node可执行文件的path,nodeJS会抛出一个错误,它找不到.js文件。

所以,我正在寻找的是获得正在运行的node可执行文件的绝对path,然后编译.js文件的绝对path,我必须将其作为参数添加到node命令。

是否有一种方法可以在Java平台不可知的情况下做到这一点? 我意识到我可以运行where node ,得到输出,并从那里,但我不想硬编码特定于操作系统的命令。

这是我的代码到目前为止:

 CommandLine cmdLine = new CommandLine("node"); cmdLine.addArgument("D:/SDKs/Appium/node_modules/appium/lib/server/main.js"); cmdLine.addArgument("--address"); cmdLine.addArgument("0.0.0.0"); cmdLine.addArgument("--port"); cmdLine.addArgument("4444"); cmdLine.addArgument("--app"); File app = new File("some.apk"); cmdLine.addArgument(app.getAbsolutePath()); cmdLine.addArgument("--app-pkg"); cmdLine.addArgument("some.stuff.does.not.matter"); cmdLine.addArgument("--pre-launch"); cmdLine.addArgument("--automation-name"); cmdLine.addArgument("Appium"); System.out.println(cmdLine.toString()); DefaultExecutor executor = new DefaultExecutor(); ExecuteWatchdog watchdog = new ExecuteWatchdog(60000); executor.setWatchdog(watchdog); try { int exitValue = executor.execute(cmdLine); } catch (IOException e) { System.err.println("Error starting Appium: " + e.getMessage()); 

注意D:/SDKs/Appium/node_modules/appium/lib/server/main.js ? 我需要以智能的方式来构build,以消除硬编码。

你必须自己扫描$ PATH。 这是演示 (在github上托pipe)

关键是:

 System.getenv("PATH") .split(System.getProperty("path.separator")) 

剩下的就是在每个path上search一个名为“node”的文件。