I work under Windows 8.1 operating system. Inside there I have a .bat file called test.bat which simply executes an echo command:
echo "123" > output.txt
Whenever I run the file from the command line (cmd.exe) it creates a text file called output.txt where "123" is written into (I'm supposing the file does not exist every time the .bat is called for simplicity).
The .bat runs OK everytime I call it from the command line, but when I try to call it from Java source code, the .bat does not execute, even though the code runs OK (or it seems to, because no warning or error code is shown).
My Java source code goes as this:
import java.io.*;
import java.util.*;
public class HelloWorld {
public static void main(String[] args) throws InterruptedException{
try
{
List<String> command_args = Arrays.asList("cmd.exe", null , " "test.
File dir = new File("C:\\Users\\Administrador\\workspace\\test\\src\\test");
String[] files = dir.list();
Runtime.getRuntime().exec("cmd /c test.bat", null, new File("C:\\Users\\Administrador\\workspace\\test\\src\\test"));
if( files.length == 0 )
{
System.out.println("Empty dir");
}
else
{
for( String f: files )
{
System.out.println(f);
}
}
ProcessBuilder pb = new ProcessBuilder( command_args );
pb.directory(dir);
Process proc = pb.start();
//int error = proc.waitFor();
}
catch( IOException ioe)
{
ioe.printStackTrace();
}
}
}
The file is called HelloWorld.java and is found inside the route C:\Users\Administrador\workspace\test\src\test. Some of the lines of the code are used to list the contents of the directory referenced by the variable dir, which indeed points to the right directory, as the output of the code shows the files inside the directory (both HelloWorld.java and test.bat ).
If I run the code it prints the directory contents correctly and also seems to execute 100% of the code, but there is no output.txt file created everytime I run the Java code. I'm trying two different ways to run the .bat from Java, both using ProcessBuilder
and directly from Runtime, but neither one of those get the expected result.
Do you know if it's possibly to fully run this kind of .bat from Java or if I need to use a specific library for it?
Thanks in advance.