I have directory which is used to temporary store images while working with them. Once all process are done and images are not need it anymore I would like to delete them. I tried following code but it didn't work.
Where is problem?

Runtime comPrompt = Runtime.getRuntime();
String[] execStr = {"C:/WINDOWS/system32/cmd.exe", "del C:/Temp/*.tif", "exit"};
comPrompt.exec(execStr);

Have you tried File class?

File filePath = new File("C:/Temp/");
File[] files = filePath.listFiles(tifFilter);
 
files[0].delete();
files[1].delete();
...

Yes did, but it not always work...

File d;
for(int i = 0; i < myImgSplit.length; i ++)
{
	System.out.println(myImgSplit[i]);
	d = new File(myImgSplit[i]);
	try
	{
		d.delete();
	}
	catch(SecurityException se)
   	{
		se.printStackTrace();
	}	    		
}
try
{
	System.out.println("DELETE DIRECTORY");
	myDir.delete();
}
catch(SecurityException se)
{
	se.printStackTrace();
}

The following is taken from Java API for Runtime class.

------------------

Every Java application has a single instance of class Runtime that allows the application to interface with the environment in which the application is running. The current runtime can be obtained from the getRuntime method. An application cannot create its own instance of this class.

--------------------------

  1. You cannot obtain an exit status from an external process until it has exited
  2. You must immediately handle the input, output, and error streams from your spawned external process
  3. You must use Runtime.exec() to execute programs
  4. You cannot use Runtime.exec() like a command line

Still in process of learning Java, so if you put this in the appropriate code I will appreciate it

in general: Do NOT use that. There's almost never a need to use Runtime.exec or any of the other methods from the Runtime class unless maybe you're writing a compiler or classloader.

Using File works fine, IF you have rights to delete the files.
If you don't, running a del command should not work either.

As it is in development all testing is done on my pc where I have all admin rights. Working with Windows XP...

As it is in development all testing is done on my pc where I have all admin rights. Working with Windows XP...

If that's the case things should've worked. But you say it didn't. Post the errors you got (stack trace...).

Problem with Runtime.getRuntime().exec(string_cmd) ; is that string_cmd differs from platform to platform, so your program won't run on a Unix machine. That's why ppl say don't use it. If you don't care, go ahead and use it, just remember you're also missing on a learning opportunity.. :)

If that's the case things should've worked. But you say it didn't. Post the errors you got (stack trace...).

Problem with Runtime.getRuntime().exec(string_cmd) ; is that string_cmd differs from platform to platform, so your program won't run on a Unix machine. That's why ppl say don't use it. If you don't care, go ahead and use it, just remember you're also missing on a learning opportunity.. :)

If I had any errors I would already posted. Problem is that "for loop" which I posted few post above run without any problems regarding to error messages but it doesn't do it job. No files are deleted.

Second think, I'm not dump to not know that Runtime which I tried to implement wouldn't work on Unix so you don't have to moke me

so you don't have to moke me

That sure wasn't the intention. What was meant is "if you don't care [whether your program runs on Unix or not]...". Which could simply be due to requirements.

Anyway, just remembered that Runtime would create some streams (for input, output and error streams of the newly created process using exec()). You'll have to read (writing is not needed in your case) from this stream and print out all that's read. Then you'll have some errors to report. So in case your command "del C:\\Temp\\xyz" failed and printed out some errors you can read them from the stream that Runtime gives you.

I had some sample code, will dig it and post if I can find it.

Hope things are clear from comments in the code..
Ignore the part where password is passed to child proc (in my case the command that I execute using Runtime.exec() expects a password to be input by user on command line).

// String storing the command to be executed
String lCmdStrStr = lStrBuf.toString();
sLogObj.writeLog(sLogObj.INFO,"JTrcMgrAnalyzeCom -> Executing: "+lCmdStrStr);
Process lChldProc = Runtime.getRuntime().exec(lCmdStrStr);
// Sending the password to the perl script
if(lNeedFtpBool)
{
    BufferedWriter lPout = new BufferedWriter(new OutputStreamWriter(lChldProc.getOutputStream()));
    lPout.write(lMypwdStr);
    lPout.flush();
    lPout.close();
}
// Wait for the child to exit
lChldProc.waitFor();
// Get the exit status of the child process
int lStatIntInt = lChldProc.exitValue();
BufferedReader lChldProcOutStream = new BufferedReader(new InputStreamReader(lChldProc.getInputStream()));
String lChldProcOutPutStr = null;
while ((lChldProcOutPutStr = lChldProcOutStream.readLine()) != null)
{
    System.out.println(lChldProcOutPutStr);
}
lChldProcOutStream.close();
//*************************************************************************************
// After checking the return code from the child proc, print a shell window msg
// indicating the success or failure
//*************************************************************************************
if( lStatIntInt != 0)
{
    // Print a shell window message indicating the failure
    System.out.println("Error  : Failed to execute the analyze command. Please try again.");
    sLogObj.writeLog(sLogObj.INFO,"JTrcMgrAnalyzeCom -> Failed to exec the analyze cmd, exit code of child is:"+lStatIntInt);
}

Well, I can't. Anyway it's not encouraged to chat elsewhere so that solutions can remain here..
I'll try to explain once more:
If you do Runtime.exec("dir"); in your code and run it, you will NOT see the directory listing prited by dir command, this is because of the way Runtime executes the command.
To execute a given command Runtime creates a child process and creates an OutputStream object that is attached to this child process's output file descriptor/stream. So whatever is prited out by the command goes to this stream object and not on the console where you are running your java program.
So finally to get what was printed by your command, you need to read from that OutputStream and print whatever you read using System.out.println().
Here is the sample code doing exactly what I explained above:

// String storing the command to be executed
String lCmdStrStr = lStrBuf.toString();
sLogObj.writeLog(sLogObj.INFO,"JTrcMgrAnalyzeCom -> Executing: "+lCmdStrStr);
Process lChldProc = Runtime.getRuntime().exec(lCmdStrStr);

// Wait for the child to exit
lChldProc.waitFor();
BufferedReader lChldProcOutStream = new BufferedReader(new InputStreamReader(lChldProc.getInputStream()));
String lChldProcOutPutStr = null;
while ((lChldProcOutPutStr = lChldProcOutStream.readLine()) != null)
{
    System.out.println(lChldProcOutPutStr);
}
lChldProcOutStream.close();

I reused your code but I think ( I know there is a mistake somewhere) I didn't get it worning properly

Here is code as I have it

try
{
    // String storing the command to be executed
       String lCmdStrStr = "C:/WINDOWS/system32/cmd.exe";
        Process lChldProc = Runtime.getRuntime().exec(lCmdStrStr);
        
        BufferedWriter lPout = new BufferedWriter(new OutputStreamWriter(lChldProc.getOutputStream()));
        String getDir = "cd C:/Temp";
    lPout.write( getDir, 0, getDir.length()-1);
        lPout.flush();
    String delCom = "del *.tif";
    lPout.write( delCom, 0, delCom.length()-1);
    lPout.flush();
    lPout.close();
            
    // Wait for the child to exit
    lChldProc.waitFor();
    BufferedReader lChldProcOutStream = new BufferedReader(new InputStreamReader(lChldProc.getInputStream()));
    String lChldProcOutPutStr = null;
    while ((lChldProcOutPutStr = lChldProcOutStream.readLine()) != null)
    {
        System.out.println(lChldProcOutPutStr);
    }
    lChldProcOutStream.close();
}
catch(Exception e)
{
    e.printStackTrace();
}

but it does not delete tif files from directory. System.out.println(lChldProcOutPutStr); only print out C:\Project\EDMA>More? what is project directory and More? which is related to cmd not understanding my command

Can you please let me know what I'm doing wrong?
Thank you
Peter

I think this is your problem is the command:

String lCmdStrStr = "C:/WINDOWS/system32/[B]cmd.exe[/B]";

PS: I've never used Runtime on windows. Problem is you're trying to use a built-in command of cmd.exe instead of a seperate command which has an executable of it's own.

Anyway your problem is that when you run cmd.exe you see the prompt ! (that "C:\Project\EDMA>" is the command prompt where cmd.exe, the child process, is waiting for you to type commands.)
There are 2 ways of doing this: easy and hard. :)
Hard way is connect to the lChldProc.getInputStream() and write your command into it. So Runtime will pass it on to cmd.exe and it'll execute the command.
Easy way is have a look at "help cmd" and see the description of "/C switch/option".

Problem was in String getDir = "cd C:/Temp"; I used wrong slash, well sort of. I try to avoid error with escape character and I used Unix way which I know is working on Windows too. However this was directly passed to command line. So solution is

String getDir = "del C:" + File.separator + "Temp" + File.separator + "*.tif";
lPoutWriter.write( getDir, 0, getDir.length());
lPoutWriter.newLine();
lPoutWriter.flush();
lPoutWriter.close();

So now code is working. However I come with new chalenge.

What I'm trying, is to delete images which my application saved in Temp previously. But I'm getting deadlock. Looks like some of images are still in use and they can't me deleted, so naturaly command prompt never ends. I know it would be suitable to use threads but it is to early for me start to work with them. So is there any simple way to chceck if images are in use, so I can delete them without any problems?

A note on the file separator, the command line intrepreter is the complete reason why "\" is always used on Windows. Almost, if not, all programming languages can use "/" for paths in Windows, but the command line interpretor interprets "/" as the option argument indicator, so it needs something else for the file separator, and that became "\".

I have a similar problem that I hope someone can help me. I am trying to copy a file using a different user name / pwd than the one I used to log into Windows with. I am using the runas.exe to do this and I am using java's Runtime.process.exec() to launch runas.exe

I think the problem is that I am not sending the password correctly to RuntimeProcess's writer. Any ideas?

Thanks

Uday

Here are some code snippets:

Runtime rt = Runtime.getRuntime();
String [] cmd = {"cmd.exe", "/C","D:/Development/saveReport.bat"};

Process process = rt.exec(cmd);
// Send the password to the password
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(process.getOutputStream()));
writer.write("mypwd");
writer.flush();
writer.close();

StreamConsumer errorConsumer = new StreamConsumer(process.getErrorStream(), "ERROR");            

// any output?
StreamConsumer outputConsumer = new StreamConsumer(process.getInputStream(), "OUTPUT");

// kick off the consumer threads
errorConsumer.start();
outputConsumer.start();
            
// wait for process to complete
int exitValue = process.waitFor();
System.out.println("exit value " + exitValue);

// StreamConsumer class
class StreamConsumer extends Thread {
    InputStream is;
    String type;

    StreamConsumer(InputStream is, String type) {
        this.is = is;
        this.type = type;
    }

    public void run() {
        try {
            InputStreamReader isr = new InputStreamReader(is);
            BufferedReader br = new BufferedReader(isr);
            String line=null;
            while ( (line = br.readLine()) != null)
                System.out.println(type + ">" + line);
            br.close();
            isr.close();
        } catch (IOException ioe) {
            ioe.printStackTrace();  
        }}}

Batch file is pretty simple
runas /user:domain\uname /pwd:pword "xcopy.exe C:\report.log
\\consult2\finalDest /i"

This question has already been answered. Start a new discussion instead.