Linux 命令无法使用 java 如果它包含特殊符号
Linux Command not working using java if it contains special symbol
我正在尝试 运行 下面的代码,但它不起作用,谁能帮我理解为什么它会这样,或者我是否遗漏了什么?
import java.io.IOException;
public class SimpleClass {
public static void main(String args[]){
try {
Process process = Runtime.getRuntime().exec("bash mkdir demoDir");
// Process process2 = Runtime.getRuntime().exec("echo sometext >> someFile.txt");
}
catch (IOException e) {
e.printStackTrace();
}
}
}
如果我执行第一个进程,它工作正常,但如果我执行进程 2,它就不起作用。 someFile.txt 存在并且当前工作目录,除了这个命令,如果我尝试创建像 mkdir /home/dummy/demoDir
这样的目录,那么它也不起作用,但我的程序成功执行。
>>
由您的 shell 解释和处理(例如,bash、zsh 等)。但是,您在此命令中不是 运行 a shell。 Runtime.exec()
基本上执行命令 /bin/echo
并将参数传递给它 someText
、>>
、someFile.txt
.
我不知道你为什么想做你正在做的事情,但试试这个:
Runtime.getRuntime().exec("bash -c \"echo sometext >> someFile.txt\"");
没有 shell 就不能执行 echo 命令 -> 添加 bash 到 th
的开头
这个问题的答案已经讨论过here。使用
String[] cmd = {"bash", "-c", "echo sometext >> someFile.txt" };
Process process2 = Runtime.getRuntime().exec(cmd);
相反。适合我。
我正在尝试 运行 下面的代码,但它不起作用,谁能帮我理解为什么它会这样,或者我是否遗漏了什么?
import java.io.IOException;
public class SimpleClass {
public static void main(String args[]){
try {
Process process = Runtime.getRuntime().exec("bash mkdir demoDir");
// Process process2 = Runtime.getRuntime().exec("echo sometext >> someFile.txt");
}
catch (IOException e) {
e.printStackTrace();
}
}
}
如果我执行第一个进程,它工作正常,但如果我执行进程 2,它就不起作用。 someFile.txt 存在并且当前工作目录,除了这个命令,如果我尝试创建像 mkdir /home/dummy/demoDir
这样的目录,那么它也不起作用,但我的程序成功执行。
>>
由您的 shell 解释和处理(例如,bash、zsh 等)。但是,您在此命令中不是 运行 a shell。 Runtime.exec()
基本上执行命令 /bin/echo
并将参数传递给它 someText
、>>
、someFile.txt
.
我不知道你为什么想做你正在做的事情,但试试这个:
Runtime.getRuntime().exec("bash -c \"echo sometext >> someFile.txt\"");
没有 shell 就不能执行 echo 命令 -> 添加 bash 到 th
的开头这个问题的答案已经讨论过here。使用
String[] cmd = {"bash", "-c", "echo sometext >> someFile.txt" };
Process process2 = Runtime.getRuntime().exec(cmd);
相反。适合我。