简体   繁体   English

使用Java程序运行批处理文件

[英]Run a batch file with java program

try {                               
try {
    String[] command = {"cmd.exe", "/C", "Start", "D:\\test.bat"};
        Runtime r = Runtime.getRuntime();
        Process p = r.exec(command);
        p.waitFor();

    } catch (Exception e) {
        e.printStackTrace();
        JOptionPane.showMessageDialog(this, "Error" +"Execution!","Error",JOptionPane.ERROR_MESSAGE);
        }
    } catch (IOException ex) {
        Logger.getLogger(DBBackUp.class.getName()).log(Level.SEVERE, null, ex);
    }

When I run this code, I got only command promt. 当我运行这段代码时,我只有命令提示符。 .bat file is not running. .bat文件未运行。 How can I execute the batch file using this code? 如何使用此代码执行批处理文件?

Thank in Advance 预先感谢

考虑使用Apache Commons Exec

let your "test.bat" be like this: 让您的“ test.bat”如下所示:

dir
pause

then you can execute this batch file as follows: 那么您可以按以下方式执行此批处理文件:

try
{
 Runtime r = Runtime.getRuntime();
 Process p = r.exec("rundll32 url.dll,FileProtocolHandler " + "D:\\test.bat");
 p.waitFor();
}catch(Exception ex){ex.printStackTrace();}

You can try something like this: 您可以尝试如下操作:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;


public class BatchExecuteService {

    public static void main(String[] args) {
        BatchExecuteService batchExecuteService = new BatchExecuteService();
        batchExecuteService.run();
    }

    public void run() {
        try {
            String cmds[] = {"D:\\test.bat"};
            Runtime runtime = Runtime.getRuntime();
            Process process = runtime.exec(cmds);
            process.getOutputStream().close();
            InputStream inputStream = process.getInputStream();
            InputStreamReader inputstreamreader = new InputStreamReader(inputStream);
            BufferedReader bufferedrReader = new BufferedReader(inputstreamreader);
            String strLine = "";
            while ((strLine = bufferedrReader.readLine()) != null) {
                System.out.println(strLine);
            }
        } catch (IOException ioException) {
            ioException.printStackTrace();
        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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