简体   繁体   中英

How to run a .bat file with pause and proceed in java

I have a utility which processes multiple csv files. The actual scenario is:

  1. Run the .bat file.
  2. When file1.csv is processed, .bat file is paused and shows us the option to verify the output and press enter to continue with file2.csv.
  3. Like wise it goes for multiple files.

Now I need to automate this process of executing .bat file with pause and proceed. Currently, I can execute the .bat file in below way:

String cmd = "cmd /c run.bat");
Process p = Runtime.getRuntime().exec(cmd);
p.waitFor();

Kindly help with pause and proceed option.

EDIT: While at Pause, I call a sub thread to verify the output(currently working with verifying the output automatically). Say if the output was TRUE, then I need to proceed with .bat file or else, terminate.

Here is a short POC according to ur needs . You can modify it.

.bat file

 @echo off @echo hi @echo File 1 underReview @echo Press 0 to continue PAUSE @echo Done Review.. PAUSE

Java File BatchAutomateInput

public static void main(String[] args) throws IOException, InterruptedException {
    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

    ProcessBuilder pb = new ProcessBuilder("cmd", "/c", "BATInput.bat");
    File dir = new File("C:\\BatTest");
    pb.directory(dir);
    Process p = pb.start();
    InputStream out = p.getInputStream();   
    OutputStream outConsole=p.getOutputStream();

        BufferedReader in = new BufferedReader(new InputStreamReader(out));
        //BufferedWriter bout = new BufferedWriter(new OutputStreamWriter(outConsole)); 
        PrintWriter bout = new PrintWriter( p.getOutputStream() );
        String line = null;

        while ((line = in.readLine()) != null) {
            if (line.trim().length() > 0) {
                System.out.println(line);
                if(line.contains("Press 0"))
                {
                    int i=Integer.parseInt(br.readLine());
                    bout.write(i);
                    bout.write("\n");
                    bout.flush();
                }
            }
        }

        System.out.println("Executed Sucessfully");


}

Output Java Console

 hi File 1 underReview Press 0 to continue 0 Press any key to continue . . . Done Review.. Press any key to continue . . . Executed Sucessfully

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