2016-12-18 35 views
0

这是一台Linux机器,下面的代码不会导致任何输出,我很好奇为什么。 P.S. - 我没有阅读关于需要转义的代字号,但是在任何情况下都用反斜杠和javac指出了语法错误。Runtime.getRuntime().exe(“ls〜”)没有列出主目录的内容

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

class Run { 
    public static void main(String args[]) throws IOException { 
     Process p = Runtime.getRuntime().exec("ls ~"); 
     BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream())); 
     String line; 

     while ((line = br.readLine()) != null) { 
      System.out.println(line); 
     } 
    } 
} 
+1

'〜'由外壳插做到这一点。 – chrylis

+0

'Process process = Runtime.getRuntime()。exec(new String [] {“/ bin/sh”,“-c”,“ls〜”});'调用你的shell并在传递之前展开'〜'它到'ls'。 – teppic

+0

另请参见[当Runtime.exec()不会](http://www.javaworld.com/article/2071275/core-java/when-runtime-exec---won-t.html)很多很好的有关正确创建和处理过程的提示。然后忽略它是指'exec'并使用'ProcessBuilder'来创建进程。还要将'String arg'分解为'String [] args'来解释包含空格字符的路径。 –

回答

1

这是因为~被shell的路径替换为您的主目录的路径。你没有使用shell。相反,它就像你跑ls '~',这给出了错误:

ls: cannot access '~': No such file or directory 

事实上,你可以看到只是当你改变这种情况发生p.getInputStream()p.getErrorStream(),这使你的程序的输出:

ls: cannot access '~': No such file or directory 
1

你需要~由shell插入以获取home文件夹,而不是您可以从系统属性中读取user.home,如

Process p = Runtime.getRuntime().exec("ls " + System.getProperty("user.home")); 

你也可以用ProcessBuilder

ProcessBuilder pb = new ProcessBuilder("ls", System.getProperty("user.home")); 
pb.inheritIO(); 
try { 
    pb.start().waitFor(); 
} catch (InterruptedException e) { 
    e.printStackTrace(); 
} 
相关问题