21

I just want to execute my file from a specific folder. in my case /data/data/my-package/files/. So i tried :

 Process process2=Runtime.getRuntime().exec("cd /data/data/my-package/files/");
 process2.waitFor();
 process2=Runtime.getRuntime().exec("./myfile");

It doesn't work. could anyone tell me please the right way to do that . Thanks

Dmitry Ginzburg
  • 7,391
  • 2
  • 37
  • 48
113408
  • 3,364
  • 6
  • 27
  • 54
  • does `....exec("/data/data/my-package/files/myfile");` work? – zapl May 21 '12 at 16:46
  • it work but here i want to exec my file from specified folder because it generate a new file. thanks – 113408 May 21 '12 at 17:00
  • You can see [my answer][http://stackoverflow.com/questions/6811522/changing-the-working-directory-of-command-from-java/42281455#42281455] – David Hazani Feb 16 '17 at 18:17

3 Answers3

44

It should be possible to call the executable with a specific working directory using Runtime.exec(String command, String[] envp, File dir)

as follows:

Process process2=Runtime.getRuntime().exec("/data/data/my-package/files/myfile",
        null, new File("/data/data/my-package/files"));

maybe without the full path to myfile

Process process2=Runtime.getRuntime().exec("myfile",
        null, new File("/data/data/my-package/files"));

Context#getFilesDir() instead of hardcoding the path should work too and is safer / cleaner than specifying the path yourself since it is not guaranteed that /data/data/.. is always the correct path for all devices.

Process process2=Runtime.getRuntime().exec("myfile",
        null, getFilesDir()));

The problem with cd somewhere is that the directory is changed for a different Process so the second call to exec in a new Process does not see the change.

zapl
  • 63,179
  • 10
  • 123
  • 154
2

It works for me when I use the following overloaded method:

public Process exec(String command, String[] envp, File dir)

For example:

File dir = new File("C:/Users/username/Desktop/Sample");
String cmd = "java -jar BatchSample.jar";
Process process = Runtime.getRuntime().exec(cmd, null, dir);

The command just stores the command you want to run in command line. dir just stores the path of your .jar file to be executed.

user3437460
  • 17,253
  • 15
  • 58
  • 106
0

A different solution will be,

Execute a .bat file from the Java Code

And do all the directory change, and stuff inside the bat file

For instance, my execute.bat file looks like this,

cd flutter_app
flutter build apk
cd ..

And the Java code looks like this,

Process process = Runtime.getRuntime().exec("execute.bat");
Dharman
  • 30,962
  • 25
  • 85
  • 135
Ashwin Balani
  • 745
  • 7
  • 19