【问题标题】:Running Runnable with different working directory使用不同的工作目录运行 Runnable
【发布时间】:2012-05-03 12:20:51
【问题描述】:

在我的程序中,我想用不同的工作目录执行一些函数(我已经加载了使用当前目录中的文件并想要执行它的 JAR)

有没有办法通过设置工作目录来执行 Runnable 或 Thread 或其他对象?

【问题讨论】:

标签: java


【解决方案1】:

不,工作目录与操作系统级别的进程相关联,您不能在程序的一部分中更改它。您将不得不更改获取目录的方式。

(我假设您当前使用 System.getProperty("user.dir") 获取目录,或者调用类似从环境中获取目录的代码。)

澄清:您当然可以全局更改属性,但随后它会在所有线程中更改。我认为这不是您想要的,因为您谈论的是线程。

【讨论】:

    【解决方案2】:

    您不能为线程设置工作目录,但是您可以使用不同的工作目录创建新进程。 在此处查看示例: http://docs.oracle.com/javase/1.5.0/docs/api/java/lang/ProcessBuilder.html

    您还可以创建具有要使用的目录概念的特定类型的线程。 例如:

    public class MyThread extends Thread
    {
       private final String workingDir;
    
       public MyThread(String workingDir)
       {
            this.workingDir = workingDir;
       }
    
       public void run()
       {
           //use the workingDir variable to access the current working directory
       }
    }
    

    【讨论】:

      【解决方案3】:

      如果您将user.dir 设置为System.setProperty(),它可能会起作用

      我想你可以用下面的例子来改变它:

      public static void main(String[] args) {
      
          System.out.println("main: " + new File(".").getAbsolutePath());
          System.setProperty("user.dir", "C:/");
          Runnable r = new Runnable() {
              public void run() {
                  System.out.println("child: "+new File(".").getAbsolutePath());
              }
          };
      
          new Thread(r).start();
      
          System.out.println("main: "+new File(".").getAbsolutePath());
      
      }
      

      这将产生:

      主要:C:\Projekte\Techtests。

      主:C:\。

      孩子:C:\。

      【讨论】:

      • 好的,但我认为问题的意思是在不同的线程中有不同的工作目录。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-09-13
      • 2016-04-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多