Skip to Main Content

Java Programming

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

Executing a windows batch file (with parameters having spaces)

807603Jan 3 2008 — edited Jan 11 2008
Hi all,

/* I know that this issue has been raised quite many a time, so please pardon me for the redundancy. I haven't got a satisfactory solution yet */

Suppose I have a batch file Test.bat in E:\My Project\
Let the syntax for calling the script be: Test -F <directory>
where +<directory>+ is the absolute path of a directory to be created (assuming its parent exists)

In case I want to execute the following statement through code,

E:\My Project\Test.bat -F E:\My Project\Demo

what would be the right way of doing this?

In particular, can anyone tell me how can we pass arguments having space characters to a batch file?

I am posting some test code for convenience:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class Tester
{
	public static void main(String[] args) throws Exception
	{
		String exePath = "E:\\My Project\\Test.bat";
		String dirPath = "E:\\My Project\\Demo";
		ProcessBuilder pb = new ProcessBuilder("cmd", "/c", exePath, "-F", dirPath);
		final Process proc = pb.start();
                //A thread that empties the error stream and writes to the console
		new Thread()
		{
			public void run()
			{
				BufferedReader br = new BufferedReader
					(new InputStreamReader(proc.getErrorStream()));
				String line;
				try
				{
					while (null != (line = br.readLine()))
						System.out.println(line);
				}
				catch(IOException e)
				{
					e.printStackTrace();
				}
				finally
				{
					if (null != br)
					{
						try
						{
							br.close();
						}
						catch(IOException e)
						{
							e.printStackTrace();
						}
					}
				}
			}
		}.start();
		int retCode = proc.waitFor();
		System.out.println("Return: " + retCode);
	}

}
Also create a "Test.bat" with the contents
mkdir %2

Thanks in advance.

Regards,
Kumar.
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Feb 8 2008
Added on Jan 3 2008
10 comments
2,200 views