Run command line operations from Java
I built a very simple program to test the command line operation of running Java That is: later, I hope to modify this code and use "move" to any other command I can enter the command line (including calling other non Java Software)
I did search and read about twenty answers, but they all suggested that I try this correctly, which is irrelevant to my simple test, or propose other solutions that don't work (such as using the. Exec (string []) method instead of Exec (string) – same result!)
This is my code:
import java.io.IOException; public class RunCommand { private static final String PATH_OUT = "C:\\Users\\me\\Desktop\\Temp\\out\\"; private static final String FILE = "sample.txt"; private static final String PATH_IN = "C:\\Users\\me\\Desktop\\Temp\\in\\"; public static void main(String[] args) { try { String command = "move "+PATH_IN+FILE+" "+PATH_OUT; System.out.println("Command: "+command); Runtime.getRuntime().exec(command); } catch (IOException e) { e.printStackTrace(); } } }
This is the output I see when I run:
Command: move C:\Users\myingling\Desktop\CDS\Temp\in\sample.txt C:\Users\myingling\Desktop\CDS\Temp\out\ java.io.IOException: Cannot run program "move": 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 RunCommand.main(RunCommand.java:13) 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) ... 5 more
Note that when I copy / paste a command into a command prompt window, the file moves successfully
What did I miss? All the other questions I've read seem to suggest that this should work
thank you!
The editor is working now. Thank you for your help! Annoyingly, it hides "move" CMD Exe parameter I hope they're calling The exec() method is valid for copy / paste All right.
Solution
The "move" command is CMD Exe is part of the interpreter, not an executable
This works:
cmd.exe /c move file1 file2