简体   繁体   中英

Runtime exec cannot run programs in appdata?

I have been messing around with running some .exe files and it appears as if there is something blocking it from running it in appdata?

Runtime.getRuntime().exec(System.getenv("APPDATA") + "test.exe");

This is the error I get

java.io.IOException: Cannot run program "C:\Users\Cole": CreateProcess error=2, The system cannot find the file specified

You should not use the plain exec(String) method as it requires OS specific escaping. If you use the string array version it should find the executable.

It is also a good idea to check if the variable exists and if it ends with a \\ before concatenating it with the filename. Or better use the hierachical File constructor:

String appdata = System.getenv("APPDATA");
if (appdata == null || appdata.trim().isEmpty())
  appdata=".";
String fileName = new File(appdata, "test.exe").getAbsolutePath();
Runtime.getRuntime().exec(new String[]{fileName /*, noargs */});

An easy way to do this is to construct the path using a File object.

final String f = new File(System.getenv("APPDATA"), "test.exe").toString();
final Process p = Runtime.getRuntime().exec(new String[] { f });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM