execute file from defined directory with Runtime.getRuntime().exec

前端 未结 3 1097
时光取名叫无心
时光取名叫无心 2020-12-29 05:31

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         


        
3条回答
  •  隐瞒了意图╮
    2020-12-29 06:27

    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.

提交回复
热议问题