Runtime Exec seems to be ignoring apostrophes

2019-07-08 11:17发布

问题:

A simple example is trying to cd to a directory that has more than two words. When I run the below code, I don't get the expected error: /usr/bin/cd: line 2: cd: /Directory With Two Words: No such file or directory, but this error: /usr/bin/cd: line 2: cd: '/Directory: No such file or directory. So it seems like it is ignoring the apostrophes and just looking for a directory called "Directory".

Code:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class Test
{
     public static void main(String []args)
     {
        try 
        {
            Process p = Runtime.getRuntime().exec("cd '/Directory With Two Words'");
            BufferedReader stdError = new BufferedReader(new InputStreamReader(p.getErrorStream()));

            // read any errors from the attempted command
            System.out.println("Error:");
            String s = null;
            while ((s = stdError.readLine()) != null) 
            {
                System.out.println(s);
            }
        }
        catch (IOException e) 
        {
             e.printStackTrace();
        }
     }
}

回答1:

You should be using the exec(String[]) method it's far safer. So this should work without quotes or apostrophes:

Runtime.getRuntime().exec(new String[] {"cd", "/Directory With Two Words"});

Also worth taking a look at the excellent article at JavaWorld When Runtime.exec() won't.



标签: java command