Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Running a command-line operation from within Java

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.

like image 800
Bing Avatar asked Oct 29 '12 18:10

Bing


2 Answers

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 
like image 109
Werner Kvalem Vesterås Avatar answered Nov 07 '22 16:11

Werner Kvalem Vesterås


Try this:

 Runtime.getRuntime().exec("cmd.exe /c move "+PATH_IN+FILE+" "+PATH_OUT);
like image 25
Marcio Barroso Avatar answered Nov 07 '22 18:11

Marcio Barroso