Runtime Exec seems to be ignoring apostrophes

你离开我真会死。 提交于 2020-01-05 03:57:05

问题


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.



来源:https://stackoverflow.com/questions/33318236/runtime-exec-seems-to-be-ignoring-apostrophes

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!