IT is Fun

October 19, 2007

Execute command prompt thru Java

Filed under: Java — themamakcorner @ 9:00 am

import java.io.*;
import java.io.File.*;

public class TryTry
{
public static void main(String[] args) throws IOException
{
String fileName = “C:\\Documents and Settings\\User\\My Documents\\car.txt”;

String to = “C:\\Documents and Settings\\User\\My Documents\\My Videos”;

String[] commands = {“cmd”, “/c”, “copy”, fileName ,to };
Runtime.getRuntime().exec(commands);

String cmdline = “copy ” + fileName + ” ” + to;

try{

Runtime.getRuntime().exec(commands);

}
catch(Exception e)
{

e.printStackTrace();
}
}

}

4 Comments »

  1. Thanks for the little example.

    I am doing Eclipse RCP development and I need to have a Command Line interface besides the GUI.

    Being able to open files with windows associated editor through the CLI with a one liner (“cmd /c start fileName”) is really nice.

    Thanks again

    Comment by Adamos Loizou — June 4, 2008 @ 10:47 am

  2. Is there any way to get the result of the command executed to be stored to a variable .
    Ex: we will get a message the file is in use by another program if we try to run an erase comman on a open file.
    I want to get that message to a variable could you please put some light on this….

    Comment by Lakshminarayana — December 1, 2008 @ 12:19 am

  3. Sorry, i don’t really get what you mean.. Do u mind to elaborate?

    Comment by themamakcorner — December 1, 2008 @ 7:43 am

  4. thanks for this tutorial

    Comment by littlebro — February 12, 2009 @ 4:14 pm


RSS feed for comments on this post. TrackBack URI

Leave a comment

Blog at WordPress.com.