V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
V2EX 提问指南
wohenyingyu01
V2EX  ›  问与答

java 执行 terminal 命令无效

  •  
  •   wohenyingyu01 · 2014-12-23 04:38:17 +08:00 · 2033 次点击
    这是一个创建于 3414 天前的主题,其中的信息可能已经有所发展或是发生改变。

    刚学java 5个月毕业,代码如下
    public class HTMLTest {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        // TODO code application logic here
        try{            
            Runtime r=Runtime.getRuntime();
            String[] cmd={"ls","~/Desktop"};            
            Process p=r.exec(cmd);
            //p.wait();
            p.waitFor();
            InputStreamReader ir=new InputStreamReader(p.getInputStream());
            BufferedReader br=new BufferedReader(ir);
            String line=null;
            while ((line=br.readLine())!=null){
                System.out.println(line);
            }
        }
        catch (IOException e){
            e.printStackTrace();
        }
        catch(InterruptedException e){
            e.printStackTrace();
        }
    }
    

    }
    当cmd是"ls"时输出正常,可是无法添加路径参数如"~/Desktop",一加就没结果了,谷歌不到是什么问题,特来求助大神

    7 条回复    2014-12-23 19:55:58 +08:00
    KDr2
        1
    KDr2  
       2014-12-23 08:08:31 +08:00   ❤️ 1
    ~ 是由 shell 展开的,写全路径就好了。或者把 "ls ~/xx" 传给 shell 来解释,而不是直接执行ls。

    碰到这种问题从 p.getErrorStream() 读出错误信息看看会有帮助。
    clino
        2
    clino  
       2014-12-23 09:53:30 +08:00   ❤️ 1
    或者这样调用:
    sh -c "ls ~/xx"
    lihuoqingfly
        3
    lihuoqingfly  
       2014-12-23 10:30:57 +08:00   ❤️ 1
    一楼正解,上次执行python xxx.py 只能从p.getErrorStream()取到值
    wohenyingyu01
        4
    wohenyingyu01  
    OP
       2014-12-23 11:30:17 +08:00
    @KDr2 谢谢,确实是波浪号的问题,改成绝对路径就好了。但是我不知道怎么把"ls ~/xx"直接传递给shell,因为cmd那个string里面一有空格就报错,求解。。。
    wohenyingyu01
        5
    wohenyingyu01  
    OP
       2014-12-23 11:37:20 +08:00
    @clino 问题的关键是没法把指令直接传递给shell,指令里面一有空格就报错,好像java这个exec并不是直接传递指令
    KDr2
        6
    KDr2  
       2014-12-23 11:48:43 +08:00
    试试:
    String[] cmd={"sh", "-c", "'ls ~/Desktop'"};
    wohenyingyu01
        7
    wohenyingyu01  
    OP
       2014-12-23 19:55:58 +08:00
    @KDr2 谢谢,不过不行。。。。报错提示
    sh: ls ~/Desktop: No such file or directory
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   3293 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 24ms · UTC 11:26 · PVG 19:26 · LAX 04:26 · JFK 07:26
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.