简体   繁体   中英

Runtime.exec(String) limiting String

I'm trying to use the Java function Runetime.exec(String) to run a program in the startup folder of a windows 7 computer like so:

Runtime.getRuntime().exec(runner.getPath() + "\\run.bat");

And when I run this I get an error saying the command cannot be run:

Exception in thread "main" java.io.IOException: Cannot run program ""C:\Users\ly
ndsey\AppData\Roaming\Microsoft\Windows\Start": CreateProcess error=2, The syste
m cannot find the file specified

As you can see, the file name is cut off at the "\\Windows\\Start" when it should continue to "\\Windows\\Startup\\run.bat".. Is there an alternative I can use?

as i can see from the error you give, and i hope it's a copy past, you string runner.getPath() for some reason start and end with "\\"" which make the whole path invalid. check that and remove it if needed

if you have the file already and you just need it's path you can use

runner.getAbsolutePath()

also, if runner is a file, getPath will give you the file path including the path, so your code will surely won't work. instead use:

String path = runner.getPath();
path = path.substring(0, path.lastIndexOf("\\")) + "\\run.bat";
Runtime.getRuntime().exec(path);

As an alternative you can use ProcessBuilder . I feel ProcessBuilder is more safe than Runtime.getRuntime().exec http://docs.oracle.com/javase/7/docs/api/java/lang/ProcessBuilder.html

    String[] command = {"CMD", "/C", "dir"};
    ProcessBuilder pb = new ProcessBuilder( command );
    //set up your work directory if needed
    pb.directory(new File("c:\\path"));

    Process process = pb.start();

Considering runner as a File instance, this should work.

Desktop.getDesktop().open(new File(runner, "run.bat"));

It uses Desktop class instead of Runtime , so you don't have to convert your File (runner) to its String representation (which is error prone). Runner is now used 'as is' as the parent directory of the "run.bat" you want to execute.

Other advantage of Desktop class : you can now open any file you want.

You should avoid the exec(String) method, which attempts to parse the entire string into command + arguments. The safe option is exec(String[]) , which presupposes the first array element is the command and the rest are arguments.

So, writing

Runtime.getRuntime.exec(new String[] { yourCommandString })

is a surefire way of getting the right message across.

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