Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java error in making file through console

I want to make a file though the cmd in java using this code

    Runtime.getRuntime().exec("mkdir C:\\Users\\Nick\\test");

and i get this annoying error:

    Exception in thread "main" java.io.IOException: Cannot run program "mkdir": 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 LFID.main(LFID.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)
... 5 more

I have no idea what's causing it so help.

By the way please don't tell me how to create a folder not through cmd, I need to do it this way. Thanks.

like image 861
Nick Nikolov Avatar asked Sep 06 '25 22:09

Nick Nikolov


1 Answers

mkdir isn't a standalone executable you can launch as a separate process - it's a command that the Windows command shell understands.

So you could run cmd.exe /c mkdir ...:

Runtime.getRuntime().exec("cmd.exe /c mkdir c:\\Users\\Nick\\test");

Or:

Runtime.getRuntime().exec(
    new String[] { "cmd.exe", "/c" "mkdir" "c:\\Users\\Nick\\test"});

... but I'd still recommend just using File.mkdir instead... why call out to an external process when you can do it within Java? (If you're going to specify an odd requirement, it helps to give some more context on it...)

like image 88
Jon Skeet Avatar answered Sep 08 '25 12:09

Jon Skeet