0

I wrote a batch file that reads in a text file which contains a list of file name, and then delete and rename them one by one. I did this by using a for loop, and it works perfectly by double clicking it.

But when I tried to call this batch from a Java program. It's no longer working for this part:

for /f %%a in (ListFile.txt) do (
    DEL %%a
    REN %%a_NEW %%~nxa
  )

If I only specify a certain file name. It's working by calling from Java. Say,

DEL tag.jar
REN tag.jar_NEW tag.jar

The same thing happen for 'call' command. It's not working if calling from Java program, which makes me have to use 'start' command.

Can someone tell me why is it like this? How can I make it also working if calling from Java program?

Michael Myers
  • 188,989
  • 46
  • 291
  • 292

5 Answers5

1

How are you calling it from Java?

What exactly is happening when you do?

Why do you call a batch file instead of doing the same thing in Java, when you're calling it from Java anyway?

Michael Borgwardt
  • 342,105
  • 78
  • 482
  • 720
1

You should use:

Runtime.getRuntime().exec("cmd /c update.bat");

Instead.

Here is a snippet on how to run programs from java.

And below how I test it.

import java.io.*;
public class RunIt {
    public static void main( String [] args ) throws Throwable   { 
        Process p = Runtime.getRuntime().exec( "cmd /c update.bat");
        InputStream i = p.getInputStream();
        for(  int c = 0 ; ( c =  i.read() ) > -1  ; ) {}
        i.close();
    }
}

For some reason that goes beyond my comprehension, if I don't read the input the process is not executed, that's the reason of the for loop above.

Here's my test:

C:\oreyes\samples\java\readinput>type update.bat
echo "x" >> x.txt

C:\oreyes\samples\java\readinput>dir x.txt
 Directorio de C:\oreyes\samples\java\readinput

 No se encuentra el archivo // That is file not found

C:\oreyes\samples\java\readinput>javac RunIt.java

C:\oreyes\samples\java\readinput>java RunIt

C:\oreyes\samples\java\readinput>dir x.txt

01/16/2009  11:14 AM                 6 x.txt // file created hence update.bat executed
               1 archivos              6 bytes

I hope this helps.

Community
  • 1
  • 1
OscarRyz
  • 196,001
  • 113
  • 385
  • 569
0

Maybe the current directory is not what you think so the ListFile.txt is not found.

Try something like :

set BAT_HOME=%~dp0
echo %BAT_HOME%

for /f %%a in (%BAT_HOME%\ListFile.txt) do (
    DEL %%a
    REN %%a_NEW %%~nxa
  )
RealHowTo
  • 34,977
  • 11
  • 70
  • 85
0

Process p = Runtime.getRuntime().exec("update.bat");

p.waitFor();

l_39217_l
  • 2,090
  • 1
  • 13
  • 15
0

Are you sure you're allowed to exec a BAT script? I don't think Windows treats them as first-class executables in the same way as Unix does. You may have to do something weird like:

...exec("cmd /c update.bat")
Adrian Pronk
  • 13,486
  • 7
  • 36
  • 60