Search code examples
javascriptdos

JavaScript run a DOS command using java.lang.Runtime.getRuntime()


I am trying to run a DIR command (on a folder stored in Source variable) which is called from JavaScript:

var Source = 'C:\\Test\\Files';
var CmdCommand= 'dir ' +Source+' /s /b /a-D > c:\\file.txt';

However, when I'm trying to run it from JavaScript, I do not get any error, but the DIR command does not get executed and my c:\\file.txt is empty:

ListDirectoryAndSaveItToFIle = java.lang.Runtime.getRuntime().exec(CmdCommand);

If I do a print of the CmdCommand, I get:

dir C:\Test\Files /s /b /a-D > c:\file.txt

which works just fine if I manually run it in CMD.

Any ideas about which c:\file.txt file is empty if i run it from JavaScript?


Solution

  • You can't directly run dir at all with Runtime.exec because it is not a program, but a command built in to the command interpreter. You must run it via cmd like this:

    cmd /c dir C:\Test\Files /s /b /a-D > c:\file.txt
    

    Also, if you're embedding this JavaScript source in a Java string literal, make sure to double-escape backslashes. \f, for example, is a JavaScript escape for the ASCII form feed character, so it must be escaped as \\f, which in a Java string literal must be escaped as \\\\f.

    Finally, make sure the permissions are correct (i.e., that you can write to the root of C:) and it should work.