Can anybody help me how to execute the following one
import java.io.*;
class RunCommandDemo
{
public static void main(String args[])
{
try
{
String s=null;
//System.out.println(args[0]);
String arg[]={"type","D:/Anji/JavaExamples/MyFile.txt"};
Process p=Runtime.getRuntime().exec(arg);
BufferedReader bf=new BufferedReader(new InputStreamReader(p.getInputStream()));
while((s=bf.readLine())!=null)
System.out.println(s);
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
on execution i'm getting the following error:-
------------------------------------------
D:\Anji\JavaExamples>java RunCommandDemo
java.io.IOException: Cannot run program "type": 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 RunCommandDemo.main(RunCommandDemo.java:11)
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)
... 4 more
Note:-
----
I tried it by reading from the command line also But i couldn't get the result.

02-24-2010, 11:36 AM

Hussain Ali

which command are you using for compile and run?

02-24-2010, 11:42 AM

r035198x

You are passing the command
"type D:/Anji/JavaExamples/MyFile.txt"
and your system is telling you that there is no program called type. What did you want the program to do instead?

02-24-2010, 12:04 PM

Anjaneyulu

Actually i want to execute the MS-DOS "type" command by passing
"<file-name>" as an argument.For this in docs i found a function
java.lang.Process exec(String cmdarray[]) here,the first String reference in the cmdarray[] is a "Command" that we want to execute;subsequent String references presented in the cmdarray are the respective commands arguments.
So,I created a String array with first reference as "type" (command),Second reference as " d:\anji\JavaExamples\MyFile.txt" (which is an argument to "type" command).Hence it should execute type d:\anji\JavaExamples\MyFile.txt na?

02-24-2010, 12:19 PM

r035198x

Run the command on your command line first before writing the Java code for it.
Don't those forward slashes need to be backslashes (\) instead for Windows?

02-24-2010, 12:25 PM

Anjaneyulu

I already executed the command "type <file-name>" before posting the thread.
Now,I checked it with backslashes is well but same problem.
I changed the file-path to "d:\\anji\\JavaExamples\\MyFile.txt" here "\\" to escape the backslash in quotes.

02-24-2010, 12:38 PM

r035198x

Which command did you run successfully on your DOS prompt?

02-24-2010, 03:35 PM

Anjaneyulu

I ran the following command in DOS prompt
d:\anji\JavaExamples>type MyFile.txt
[and]
d:\anji\JavaExamples>type d:\anji\JavaExamples\MyFile.txt