有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

运行不同工作目录的java Runnable

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

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


共 (3) 个答案

  1. # 1 楼答案

    不,工作目录与操作系统级进程相关联,您不能在程序中更改它。您必须更改获取目录的方式

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

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

  2. # 2 楼答案

    如果将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());
    
    }
    

    这将产生:

    main: C:\Projekte\Techtests.

    main: C:\.

    child: C:\.

  3. # 3 楼答案

    不能为线程设置工作目录,但是可以使用不同的工作目录创建新进程。 点击此处查看示例: 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
       }
    }