Java:获得项目的绝对路径 [英] Java: get absolute path of project

查看:134
本文介绍了Java:获得项目的绝对路径的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在当前包之外的路径中运行一个exe文件。运行它的code.java文件位于

 %Workspace_path%\Project\src\main\java\\ \\com\util\code.java 

但是exe文件所在的目录

 %Workspace_path%\Project\src\main\resources\program.exe 
我正在使用Eclipse,但如果它也可以在其他IDE中使用,它将会很棒。感谢您的帮助。
解决方案

事实上,解决这个问题的办法是将EXE捆绑为一个类路径资源。看来你已经安排了这一点。



使用类路径资源时,一个成熟的程序不应该假定资源在文件系统中。资源可以打包在一个JAR文件中,甚至是一个WAR文件中。在这一点上你唯一可以信任的就是在Java中访问资源的标准方法,如下所示。

解决你的问题的方法是访问资源内容使用调用 Class.getResourceAsStream (或 ClassLoader.getResourceAsStream ),save内容到一个临时文件,并从该文件执行。这将保证你的程序不管它的包装是否正常工作。



换句话说:
$ b $ ol

  • 调用 getClass()。getResourceAsStream(/ program.exe)。从静态方法中,你不能调用 getClass ,所以使用你当前类的名字来代替,如 MyClass.class.getResourceAsStream 。这将返回 InputStream

  • 创建临时文件,最好使用 File。 createTempFile 。这将返回标识新创建文件的 File 对象。

  • 打开 OutputStream 到此临时文件。

  • 使用这两个流将资源中的数据复制到临时文件中。您可以使用 IOUtils.copy 如果你在Apache Commons工具。完成这一步后,请不要忘记关闭两个流。

  • 执行存储在临时文件中的程序。

  • 清理。


    换句话说(稍后添加代码段):

    pre > private void executeProgramFromClasspath()抛出IOException {
    //打开资源流。
    InputStream input = getClass()。getResourceAsStream(/ program.exe);
    if(input == null){
    throw new IllegalStateException(Missing classpath resource。);
    }

    //传输。
    OutputStream output = null;
    尝试{
    //创建临时文件。可能会抛出IOException。
    文件temporaryFile = File.createTempFile(getClass()。getName(),);

    output = new FileOutputStream(temporaryFile);
    output = new BufferedOutputStream(output);
    IOUtils.copy(输入,输出);
    } finally {
    //关闭流。
    IOUtils.closeQuietly(input);
    IOUtils.closeQuietly(输出);
    }

    //执行。
    尝试{
    String path = temporaryFile.getAbsolutePath();
    ProcessBuilder processBuilder = new ProcessBuilder(path);
    Process process = processBuilder.start();
    process.waitFor();
    } catch(InterruptedException e){
    //可选捕获。保持方法签名整齐。
    抛出新的IOException(e);
    } {
    //清理
    if(!temporaryFile.delete()){
    //记录这个问题,或者抛出一个错误。
    }
    }
    }


    I'm trying to run a exe file in path outside of the current package. My code.java file that runs it is in

    %Workspace_path%\Project\src\main\java\com\util\code.java
    

    However the directory of where the exe is

    %Workspace_path%\Project\src\main\resources\program.exe
    

    If possible, it seems like the best solution here would be to get the absolute path of the Project then append "src\main\resources\" to it. Is there a good way to do this or is there an alternative solution? I'm using Eclipse, but it would great if it could be used in other IDEs too. Thanks for any help.

    解决方案

    The de facto approach to solving this is to bundle the EXE as a classpath resource. It seems you have arranged for this already.

    When working with classpath resources, a mature program should not assume that the resource is in the filesystem. The resources could be packaged in a JAR file, or even in a WAR file. The only thing you can trust at that point is the standard methods for accessing resources in Java, as hinted below.

    The way to solve your problem, then, is to access the resource contents using the de facto standard of invoking Class.getResourceAsStream (or ClassLoader.getResourceAsStream), save the contents to a temporary file, and execute from that file. This will guarantee your program works correctly regardless of its packaging.

    In other words:

    1. Invoke getClass().getResourceAsStream("/program.exe"). From static methods, you can't call getClass, so use the name of your current class instead, as in MyClass.class.getResourceAsStream. This returns an InputStream.
    2. Create a temporary file, preferably using File.createTempFile. This returns a File object identifying the newly created file.
    3. Open an OutputStream to this temp file.
    4. Use the two streams to copy the data from the resource into the temp file. You can use IOUtils.copy if you're into Apache Commons tools. Don't forget to close the two streams when done with this step.
    5. Execute the program thus stored in the temporary file.
    6. Clean up.

    In other words (code snippet added later):

    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:获得项目的绝对路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

  • 查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆