Execute a CMD file stored in a JARTag(s): IO
In this example, a CMD file is stored a JAR file. The Java code extracts the file as a ressource, launch a Windows CMD Shell and write the content to the stdin without any temporary file.
In this How-to, the CMD included is used to trigger the default Windows screen saver.
scrnsave.scr /s
import java.io.*; public class StartScreenSaver { public static void main(String args[]) throws IOException { new StartScreenSaver().doit(); } public void doit() throws IOException{ String line; OutputStream stdin = null; InputStream stderr = null; InputStream stdout = null; try { // that our CMD file in our JAR InputStream is = getClass().getResource("/screensaver.cmd").openStream(); BufferedReader brCmdLine = new BufferedReader(new InputStreamReader(is)); // launch CMD and grab stdin/stdout and stderr Process process = Runtime.getRuntime ().exec ("cmd"); stdin = process.getOutputStream (); stderr = process.getErrorStream (); stdout = process.getInputStream (); // "write" the CMD file into stdin while ((line = brCmdLine.readLine()) != null) { line += "\n"; stdin.write(line.getBytes() ); } stdin.flush(); stdin.close(); // clean up if any output in stdout BufferedReader brCleanUp = new BufferedReader (new InputStreamReader (stdout)); while ((line = brCleanUp.readLine ()) != null) { //System.out.println ("[Stdout] " + line); } brCleanUp.close(); // clean up if any output in stderr brCleanUp = new BufferedReader (new InputStreamReader (stderr)); while ((line = brCleanUp.readLine ()) != null) { //System.out.println ("[Stderr] " + line); } brCleanUp.close(); } catch (IOException e) { e.printStackTrace(); } finally { stdout.close(); stderr.close(); } } }
Get the JAR here.