2
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);
    }

当我运行这段代码时,我只有命令提示符。.bat 文件未运行。如何使用此代码执行批处理文件?

预先感谢

4

3 回答 3

2

考虑使用Apache Commons Exec

于 2013-03-31T17:12:44.967 回答
1

让你的“test.bat”是这样的:

dir
pause

然后您可以按如下方式执行此批处理文件:

try
{
 Runtime r = Runtime.getRuntime();
 Process p = r.exec("rundll32 url.dll,FileProtocolHandler " + "D:\\test.bat");
 p.waitFor();
}catch(Exception ex){ex.printStackTrace();}
于 2013-03-31T15:10:07.493 回答
1

你可以尝试这样的事情:

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();
        }
    }
}
于 2013-03-31T15:20:31.767 回答