[英]How to use linux commands involving “>” through runTime.exec()
[英]Can not use && operator in Runtime.exec() + linux
我正在嘗試使用下面粘貼的代碼從Java運行可執行文件。 通過在終端中使用&&運算符,我可以使用單個命令導航到並運行可執行文件。 我試圖通過Runtime.getRuntime()。exec()命令傳遞相同的命令,但它似乎不喜歡&&運算符。 有誰知道這方面的工作? 在下面發布的代碼中,我只是將“cd && pwd”作為測試用例; 一個更簡單的命令,但它仍然無法正常工作。 謝謝
try{
int c;
textArea.setText("Converting Source Code to XML");
//String[] commands = {"/bin/bash", "-c", "cd /home/Parallel/HomeMadeXML", "&&", "./src2srcml --position" + selectedFile.getName() + "-o targetFile.xml"};
String commands = "bash -c cd && pwd";
System.out.println(commands);
Process src2XML = Runtime.getRuntime().exec(commands);
InputStream in1 = src2XML.getErrorStream();
InputStream in2 = src2XML.getInputStream();
while ((c = in1.read()) != -1 || (c = in2.read()) != -1) {
System.out.print((char)c);
}
src2XML.waitFor();
}
catch(Exception exc){/*src2srcml Fail*/}
}
您想要運行命令,您必須使用正好三個參數: bash
可執行文件, -c
執行命令的標志和第三個shell命令。
您正在嘗試傳遞5,其中最后三個是一個命令的單個片段。
這是一個例子。 注意shell命令只是一個參數:
String[] commands = { "/bin/bash", "-c", "cd /tmp && touch foobar" };
Runtime.getRuntime.exec(commands);
執行時,您將在/tmp
找到一個文件foobar
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.