Running a command-line operation from within Java

command-line, java

Solution

The "move" command is part of the cmd.exe interpreter, and not a executable by itself.

This would work:

cmd.exe /c move file1 file2 

Problem

I built a very simple program to test running a command line operation separate of Java. That is: later I want to be able to modify this code from using "move" to any other command I can enter into the command line (including calling other, non-Java, software). I did search and read probably two dozen answers, but they all either suggested I was trying this correctly, were irrelevent to my simple test or proposed other solutions which did not work (like using the .exec(String[]) method instead of .exec(String) - same result!). Here 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(); } } } ``` Here is what I see output 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 the command into a command prompt window, the file moves successfully though. What am I missing? All the other questions I've read seem to indicate this should work. Thanks! EDIT Works now, thanks for the help everyone! It's annoying that it's hidden the way "move" is a parameter of cmd.exe. I wish they had made it so if it worked when copy/pasted it worked when you called the .exec() method. Oh well.

Original source