[Java]Run batch file in Java class
มีงานที่ต้องใช้ Java ไปรัน batch ไฟล์ ในเครื่อง Windows (class นี้รันภายใต้ Windows) จากการสืบเสาะหา และ ถามไถ่จาก อ.google แล้ว ก็ได้หนทางดังนี้
/** * File Name : RuntimeExample.java * Create Date : Aug 22, 2010 13:20:26 PM */ package com.fun4station.batch; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; /** * @author Supot Saelao * @version 1.0 */ public class RuntimeExample { public static void main(String[] args) { Process process = null; BufferedReader bufferRead = null; try{ //If you don't want to see a window open //Runtime.getRuntime().exec("cmd /c start /MIN mybatch.bat"); process = Runtime.getRuntime().exec("cmd /C mybatch.bat"); bufferRead = new BufferedReader(new InputStreamReader(process.getInputStream())); String line = null; while ((line = bufferRead.readLine()) != null) { System.out.println(line); } if(process.exitValue() == 0){ System.out.println("Command start mybatch.bat sucess..."); }else{ System.out.println("Command start mybatch.bat fail..."); } }catch (Exception e){ e.printStackTrace(); }finally{ try { process.destroy(); bufferRead.close(); } catch (IOException e) {} } } }
แหล่งข้อมูล
How do I run a batch file from my Java Application?
Java Servlet – Running a batch file in Java.
No comments yet.