【问题标题】:Launch Java application (main) from specified directory从指定目录启动 Java 应用程序(主)
【发布时间】:2015-11-25 12:57:20
【问题描述】:

我有一个非常大/旧/长期运行的项目,它使用相对于启动目录的路径访问文件资源(即,应用程序只有在从特定目录启动时才能工作)。当我需要调试程序时,我可以从 eclipse 启动它并使用 Run Configurations->->Working 目录设置启动目录。我希望能够编写一个从指定目录启动主类的 Java 类。这是可能的,如果是的话我会怎么做?我找到了几个相关的项目,包括下面显示的项目,但似乎找不到我正在寻找的答案。

https://community.oracle.com/thread/1257595?start=0&tstart=0

http://www.javapractices.com/topic/TopicAction.do?Id=243

How do I run a java program from a different directory?

Java - start another class' main in a different process

【问题讨论】:

  • 也在这里讨论过(详细地)stackoverflow.com/questions/840190/…
  • ...除了(我正在阅读它),另一篇文章表明这​​是不可能的(可靠)。由于 Eclipse 确实有能力在运行配置中设置它,所以它一定是可能的。
  • Eclipse 在一个新进程中分叉了已调试的应用程序。而Runtime.exec() 确实需要一个(可选的)工作目录。 one of the answers中提到了。

标签: java


【解决方案1】:

根据this,您可以使用 main 编写一个简单的类:

  1. 请求工作目录
  2. 将您的 jar 复制到所选目录中
  3. 执行jar
  4. 从选择目录中删除 jar。

例如

public class Exec
{
   public static void main(String []args) throws Exception
    {   choosenDir=askForWorkingDirectory()
        jarFileNameWithabsolutePath=copyJarIntoDir(choosenDir)
        Process ps=Runtime.getRuntime().exec(new String[]{"java","-jar",jarFileNameWithabsolutePath});
        ps.waitFor();
        java.io.InputStream is=ps.getInputStream();
        byte b[]=new byte[is.available()];
        is.read(b,0,b.length);
        System.out.println(new String(b));
        deleteJarFormChoosenDir(jarFileNameWithabsolutePath);
    }
}

地点:

askForWorkingDirectory() 显示一个 DirectoryChooser 对话框并返回绝对路径。

copyJarIntoDir(choosenDir) 接收选择的复制jar文件的目录,并返回jar文件的绝对路径和文件名。

deleteJarFormChoosenDir(jarFileNameWithabsolutePath) 最后删除复制的jar

希望能帮到你!

【讨论】:

  • 不错的技术,但我不是从需要从 Eclipse 启动的 jar 中运行。
【解决方案2】:

将 Runtime.getRuntime.exec 与可选的运行时目录参数一起使用对我有用。

这是我用的:

public static void main(String[] args) throws Exception {
    String classPath = getClassPath();
    Runtime.getRuntime().exec("java -cp " + classPath + " com.mycompany.MyApp", null, MY_WORKING_DIR);
}

private static String getClassPath() {
    StringBuffer buffer = new StringBuffer();
    URLClassLoader urlClassLoader = ((URLClassLoader) (Thread.currentThread().getContextClassLoader()));
    URL[] urls = urlClassLoader.getURLs();
    for (URL url : urls) {
        buffer.append(new File(url.getPath()));
        buffer.append(System.getProperty("path.separator"));
    }
    String rtn = buffer.toString();
    return rtn;
}

【讨论】:

    猜你喜欢
    • 2016-12-09
    • 1970-01-01
    • 2015-08-25
    • 1970-01-01
    • 2011-11-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多