0

In my program I want to execute some function with different working directory (I've loaded JAR which working with files in current directory and want to execute it)

Is there a way to execute Runnable or Thread or some else object with setting working directory?

skayred
  • 10,603
  • 10
  • 52
  • 94

3 Answers3

1

No, working directories are associated with OS-level processes, you cannot change it in part of the program. You will have to change the way the directory is obtained.

(I assume that you currently either obtain the directory with System.getProperty("user.dir"), or invoke code that similarly gets the directory from the environment.)

Clarification: you can of course change the property globally, but then it changes in all threads. I assume that this is not what you want, since you talk about threads.

njlarsson
  • 2,128
  • 1
  • 18
  • 27
1

You can't set a working directory for a Thread, however you could create a new process with a different working directory. Check here for an example: http://docs.oracle.com/javase/1.5.0/docs/api/java/lang/ProcessBuilder.html

You could also create a specific type of thread that has the notion of the directory to use. For example:

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
   }
}
0

It may work, if you set the user.dir with System.setProperty()

I think you may change it with following example:

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());

}

This will produce:

main: C:\Projekte\Techtests.

main: C:\.

child: C:\.

Community
  • 1
  • 1
Christian Kuetbach
  • 15,850
  • 5
  • 43
  • 79
  • Ok, but I assume the meaning of the question is having different working directories in different threads. – njlarsson May 03 '12 at 12:42