我正在尝试从我的java应用程序运行命令.我从用户那里得到输入并运行这行代码:Runtime.getRuntime().exec($userInput);.我尝试过很多简单的命令,包括"echo","start chrome"和"rem".似乎唯一有效的命令是"cmd.exe",我甚至不知道它是什么.
诸如"echo"之类的命令会生成此错误:
java.io.IOException: Cannot run program "echo": CreateProcess error=2, The system cannot find the file specified
at java.lang.ProcessBuilder.start(Unknown Source)
at java.lang.Runtime.exec(Unknown Source)
at java.lang.Runtime.exec(Unknown Source)
at java.lang.Runtime.exec(Unknown Source)
at me.Draconwolver.Main.runCmd(Main.java:119)
at me.Draconwolver.Main.main(Main.java:34)
Caused by: java.io.IOException: CreateProcess error=2, The system cannot find the file specified
at java.lang.ProcessImpl.create(Native Method)
at java.lang.ProcessImpl.<init>(Unknown Source)
at java.lang.ProcessImpl.start(Unknown Source)
... 6 more
Run Code Online (Sandbox Code Playgroud)
请随时向我询问更多详情.
当我尝试创建文件时C:\ProgramData\Microsoft\Windows\Start Menu\Programs\StartUp,我收到以下错误:
java.io.FileNotFoundException: C:\ProgramData\Microsoft\Windows\Start Menu\Progr
ams\StartUp\test.bat (Access is denied)
at java.io.FileOutputStream.open(Native Method)
at java.io.FileOutputStream.<init>(Unknown Source)
at java.io.FileOutputStream.<init>(Unknown Source)
at Program.testMethod(Program.java:26)
at Program.main(Program.java:14)
Run Code Online (Sandbox Code Playgroud)
我想知道为什么我会收到此错误以及如何解决它.
当我按照下面的建议在路径周围放置引号时,我收到以下错误:
java.io.FileNotFoundException: "C:\ProgramData\Microsoft\Windows\Start Menu\Prog
rams\StartUp\test.bat" (The filename, directory name, or volume label syntax is i
ncorrect)
at java.io.FileOutputStream.open(Native Method)
at java.io.FileOutputStream.<init>(Unknown Source)
at java.io.FileOutputStream.<init>(Unknown Source)
at Program.testMethod(Program.java:26)
at Program.main(Program.java:14)
Run Code Online (Sandbox Code Playgroud)
第26行是:
BufferedWriter w = new BufferedWriter(new OutputStreamWriter(new FileOutputStream("\"C:\\ProgramData\\Microsoft\\Windows\\Start Menu\\Programs\\StartUp\\test.bat\""), "utf-8"));
Run Code Online (Sandbox Code Playgroud)