0

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.

TimeToCode
  • 901
  • 2
  • 16
  • 34
  • if you open a command line and type cmd /c test.bat does it work? if so then maybe the working directory is not set right, maybe start by executing dir and see if it shows the test.bat – Theresa Forster Oct 25 '16 at 20:40
  • @TheresaForster yes, it executes the .bat file. I also use the list() ethod from the File class in Java to list all the contents of the directory where I'm trying to call the .bat from. It prints all the files as expected so I think the directory has been set up correctly. I could be wrong of course, but how to prove it is out of the scope of my current Java knowledge. – addictedtohaskell Oct 25 '16 at 20:43
  • Try running cmd /c dir. what shows? – Theresa Forster Oct 25 '16 at 20:48
  • It output the volume label, the volume serial number and also list the current files inside the directory (HelloWorld.java and test.bat ), as well as the total number of bytes both files make in disk. – addictedtohaskell Oct 25 '16 at 20:50
  • Why are you running `cmd`? What happens if you execute the `bat` directly? – Elliott Frisch Oct 25 '16 at 20:51
  • I think there is something about runnin bat files In windows Xp you had to use exec not cmd but I think that's different now let me check – Theresa Forster Oct 25 '16 at 20:52
  • As stated in the question text, it runs OK and creates the output.txt file with the "123" string inside of it. I'm running cmd because I need to execute the .bat file from inside a Java class. – addictedtohaskell Oct 25 '16 at 20:53
  • Found it cmd /c start test.bat – Theresa Forster Oct 25 '16 at 20:54
  • Yes. And `Runtime.exec("test.bat");` does what? – Elliott Frisch Oct 25 '16 at 20:56
  • @TheresaForster I added the start word in the middle of the cmd /c command and now it works but it opens two cmd.exe windows, which I can't close manually. Do you know if there is another way to fully run the batch and after that return the control to the Java class? – addictedtohaskell Oct 25 '16 at 20:57
  • You have to exec the cmd processor but also tell it to execute as a batch file. Cmd /c is needed to start cmd.exe but then you have to use start to trigger the bat processing otherwise it will only process exec and com – Theresa Forster Oct 25 '16 at 20:58
  • @ElliottFrisch that does not work either. I already tried that but read on a previous StackOverflow question that using the 3 parameters signature of Runtime.getRuntime().exec() was a more recommended way to do it. Neither way works sadly, nor with the 1 parameter or the 3 parameters signature. – addictedtohaskell Oct 25 '16 at 20:59
  • Add "". So cmd /c start "" test.bat – Theresa Forster Oct 25 '16 at 21:01
  • @TheresaForster are those two double quotes or 4 single quotes? – addictedtohaskell Oct 25 '16 at 21:04
  • 2 " http://stackoverflow.com/questions/17201507/how-to-use-the-start-command-in-a-batch-file – Theresa Forster Oct 25 '16 at 21:05
  • It's the title of the window and if it's nothing it shouldn't show – Theresa Forster Oct 25 '16 at 21:06
  • You may need to escape them though \"\" – Theresa Forster Oct 25 '16 at 21:07
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/126665/discussion-between-addictedtohaskell-and-theresa-forster). – addictedtohaskell Oct 25 '16 at 21:08
  • Whenever you use Runtime.exec(), you need to Thread out the STDOUT and STDERR, see http://www.javaworld.com/article/2071275/core-java/when-runtime-exec---won-t.html . Also, see this post for, it may give some ideas on ProcessBuilder, http://stackoverflow.com/questions/32314645/java-processbuilder-command-arguments-with-spaces-and-double-quotes-fails – lincolnadym Oct 26 '16 at 00:50

1 Answers1

0

the code i show.it work well.

the most important is you should read the inputStream,if you don't ,it may not work success.

waitFor() make main process run until the .bat work complete.

echo helloworld >>f:/2.txt 
exit

in f:/hello.bat

Process p;
    String cmd="cmd /c start f:\\hello.bat";
    try {

        p = Runtime.getRuntime().exec(cmd);
        InputStream in = p.getInputStream();
        int c;
        while ((c = in.read()) != -1) {
                System.out.print(c);
        }
        in.close();
        try {
                p.waitFor();
        } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
        }
        System.out.println("done");

    } catch (IOException e) {
        System.out.println("play show error");
    }
李振纲
  • 372
  • 3
  • 11