简体   繁体   中英

Java - Run & use .bat file

I have a file generateK.bat , which generate key randomally.

I have two question:

  1. How can I run .bat file in java enviroment? I saw only instruction of edit the .bat file, but not run it.
  2. I want to use the key in my program. How can I use the output in java?

Thanks.

I would use Runtime.exec to exec an external program : http://docs.oracle.com/javase/1.4.2/docs/api/java/lang/Runtime.html

You will then have a Process with input and output streams that you can read/write to.

Code will look like this :

public static void main(String Argv[]) {
try {
    String ls_str;

    Process ls_proc = Runtime.getRuntime().exec("pathtoyourbat/generateK.bat");

    // get its output (your input) stream

    DataInputStream ls_in = new DataInputStream(
                                      ls_proc.getInputStream());

    try {
    while ((ls_str = ls_in.readLine()) != null) {
        System.out.println(ls_str);
    }
    } catch (IOException e) {
    System.exit(0);
    }
} catch (IOException e1) {
    System.err.println(e1);
    System.exit(1);
}

System.exit(0);
}

=> http://www.ensta-paristech.fr/~diam/java/online/io/javazine.html

There are however plenty of tutorials about running external app inside java

  1. How can I run .bat file in java enviroment? I saw only instruction of edit the .bat file, but not run it.

Use Following piece of code to run your batch file.

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

Estragon already posted answer for 2 .

从Java中, Runtime.getRuntime().exec("cmd /c start generateK.bat");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM