Java:获取项目的绝对路径
我正在尝试在当前包之外的路径中运行exe文件。 我的code.java文件运行它
%Workspace_path%\Project\src\main\java\com\util\code.java
但是exe所在的目录
%Workspace_path%\Project\src\main\resources\program.exe
如果可能的话,似乎这里最好的解决方案是获取项目的绝对路径然后将“src \ main \ resources \”附加到它。 有没有一个好方法可以做到这一点还是有替代解决方案? 我正在使用Eclipse,但如果它也可以在其他IDE中使用它会很棒。 谢谢你的帮助。
解决此问题的事实上的方法是将EXE捆绑为类路径资源。 看来你已经安排好了。
使用类路径资源时,成熟的程序不应该假定资源在文件系统中。 资源可以打包在JAR文件中,甚至可以打包在WAR文件中。 在这一点上,您唯一可以信任的是用Java访问资源的标准方法,如下所示。
那么,解决问题的方法是使用调用Class.getResourceAsStream
(或ClassLoader.getResourceAsStream
)的事实标准访问资源内容,将内容保存到临时文件,然后从该文件执行。 这将保证您的程序无论其包装如何都能正常工作。
换一种说法:
- 调用
getClass().getResourceAsStream("/program.exe")
。 从静态方法,您不能调用getClass
,因此请使用当前类的名称,如在MyClass.class.getResourceAsStream
。 这将返回一个InputStream
。 - 创建一个临时文件,最好使用
File.createTempFile
。 这将返回标识新创建文件的File
对象。 - 打开
OutputStream
到此临时文件。 - 使用这两个流将资源中的数据复制到临时文件中。 如果您使用的是Apache Commons工具,则可以使用
IOUtils.copy
。 完成此步骤后,请不要忘记关闭两个流。 - 执行存储在临时文件中的程序。
- 清理。
换句话说(稍后添加的代码段):
private void executeProgramFromClasspath() throws IOException { // Open resource stream. InputStream input = getClass().getResourceAsStream("/program.exe"); if (input == null) { throw new IllegalStateException("Missing classpath resource."); } // Transfer. OutputStream output = null; try { // Create temporary file. May throw IOException. File temporaryFile = File.createTempFile(getClass().getName(), ""); output = new FileOutputStream(temporaryFile); output = new BufferedOutputStream(output); IOUtils.copy(input, output); } finally { // Close streams. IOUtils.closeQuietly(input); IOUtils.closeQuietly(output); } // Execute. try { String path = temporaryFile.getAbsolutePath(); ProcessBuilder processBuilder = new ProcessBuilder(path); Process process = processBuilder.start(); process.waitFor(); } catch (InterruptedException e) { // Optional catch. Keeps the method signature uncluttered. throw new IOException(e); } finally { // Clean up if (!temporaryFile.delete()) { // Log this issue, or throw an error. } } }
那么,在您的上下文中,项目根目前恰好是当前路径
。
,这是java.exe开始执行的地方,所以一个简单的方法是:
String exePath="src\\main\\resources\\program.exe"; File exeFile=new File(".",exePath); System.out.println(exeFile.getAbusolutePath()); ...
我在Eclipse上测试了这段代码,没关系。 我认为应该在不同的ide上工作。 祝好运!