Here you can find the source of exec(final String cmd, final String[] args, final byte[] in, final File dir)
Parameter | Description |
---|---|
cmd | command |
args | argument array |
in | data for the standard input |
dir | working directory |
Parameter | Description |
---|---|
IOException | I/O exception |
InterruptedException | if the thread is interrupted while waiting for the process toterminate |
public static byte[] exec(final String cmd, final String[] args, final byte[] in, final File dir) throws IOException, InterruptedException
//package com.java2s; //License from project: Open Source License import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; public class Main { /** Buffer size. */ private static final int BUF_SIZ = 1024; /**/* w w w .j av a2 s .c o m*/ * Creates and runs a new {@link Process} with the given arguments, taking * {@code cmd} as a pattern for {@link String#format(String, Object...)} * with arguments {@code args}. * * @param cmd command * @param args argument array * @param in data for the standard input * @param dir working directory * @return data written to STDOUT * @throws IOException I/O exception * @throws InterruptedException * if the thread is interrupted while waiting for the process to * terminate */ public static byte[] exec(final String cmd, final String[] args, final byte[] in, final File dir) throws IOException, InterruptedException { final StringBuilder sb = new StringBuilder(); if (cmd.contains(" ")) { sb.append('"' + cmd + '"'); } else { sb.append(cmd); } for (final String arg : args) { sb.append(' ' + arg); } final Process proc = Runtime.getRuntime().exec(sb.toString(), null, dir); final OutputStream stdin = proc.getOutputStream(); if (in != null) { stdin.write(in); } stdin.close(); // handle streams final byte[] out = readFully(proc.getInputStream()); final byte[] err = readFully(proc.getErrorStream()); if (proc.waitFor() != 0) throw new IOException(cmd + " didn't return normally:\n" + new String(out) + "\n\n" + new String(err)); return out; } /** * Reads a file until EOF is reached. the stream is closed afterwards. * * @param in the file * @return read bytes * @throws IOException I/O exception */ public static byte[] readFully(final File in) throws IOException { return readFully(new FileInputStream(in)); } /** * Reads an {@link InputStream} until EOF is reached. the stream is closed * afterwards. * * @param in * input stream * @return read bytes * @throws IOException * I/O exception */ public static byte[] readFully(final InputStream in) throws IOException { final byte[] buff = new byte[BUF_SIZ]; final ByteArrayOutputStream baos = new ByteArrayOutputStream(); while (true) { final int read = in.read(buff); // does not stop when bytes not yet available if (read < 0) { break; } baos.write(buff, 0, read); } in.close(); return baos.toByteArray(); } }