java.lang.Runtime.exec()方法的使用及代码示例

x33g5p2x  于2022-01-17 转载在 其他  
字(8.2k)|赞(0)|评价(0)|浏览(172)

本文整理了Java中java.lang.Runtime.exec()方法的一些代码示例,展示了Runtime.exec()的具体用法。这些代码示例主要来源于Github/Stackoverflow/Maven等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。Runtime.exec()方法的具体详情如下:
包路径:java.lang.Runtime
类名称:Runtime
方法名:exec

Runtime.exec介绍

[英]Executes the specified program in a separate native process. The new process inherits the environment of the caller. Calling this method is equivalent to calling exec(prog, null, null).
[中]在单独的本机进程中执行指定的程序。新进程继承调用方的环境。调用此方法相当于调用exec(prog,null,null)。

代码示例

代码示例来源:origin: commons-io/commons-io

/**
 * Opens the process to the operating system.
 *
 * @param cmdAttribs  the command line parameters
 * @return the process
 * @throws IOException if an error occurs
 */
Process openProcess(final String[] cmdAttribs) throws IOException {
  return Runtime.getRuntime().exec(cmdAttribs);
}

代码示例来源:origin: gocd/gocd

public void mouseClicked(MouseEvent e) {
  // Launch Page
  try {
    Runtime.getRuntime().exec("open http://localhost:8153/go");
  } catch (IOException e1) {
    // Don't care
  }
}

代码示例来源:origin: stackoverflow.com

String[] cmd = {
"/bin/sh",
"-c",
"ls /etc | grep release"
};

Process p = Runtime.getRuntime().exec(cmd);

代码示例来源:origin: stackoverflow.com

public boolean isOnline() {

  Runtime runtime = Runtime.getRuntime();
  try {

    Process ipProcess = runtime.exec("/system/bin/ping -c 1 8.8.8.8");
    int     exitValue = ipProcess.waitFor();
    return (exitValue == 0);

  } catch (IOException e)          { e.printStackTrace(); } 
   catch (InterruptedException e) { e.printStackTrace(); }

  return false;
}

代码示例来源:origin: Alluxio/alluxio

private boolean checkSudoPrivilege() throws InterruptedException, IOException {
  // "sudo -v" returns non-zero value if the current user has problem running sudo command.
  // It will always return zero if user is root.
  Process process = Runtime.getRuntime().exec("sudo -v");
  int exitCode = process.waitFor();
  return exitCode == 0;
 }
}

代码示例来源:origin: h2oai/h2o-3

private static String getNvidiaStats() throws java.io.IOException {
 String cmd = "nvidia-smi";
 InputStream stdin = Runtime.getRuntime().exec(cmd).getInputStream();
 InputStreamReader isr = new InputStreamReader(stdin);
 BufferedReader br = new BufferedReader(isr);
 StringBuilder sb = new StringBuilder();
 String s;
 while ((s = br.readLine()) != null) {
  sb.append(s).append("\n");
 }
 return sb.toString();
}

代码示例来源:origin: libgdx/libgdx

private void generateHFile (FileDescriptor file) throws Exception {
  String className = getFullyQualifiedClassName(file);
  String command = "javah -classpath " + classpath + " -o " + jniDir.path() + "/" + className + ".h " + className;
  Process process = Runtime.getRuntime().exec(command);
  process.waitFor();
  if (process.exitValue() != 0) {
    System.out.println();
    System.out.println("Command: " + command);
    InputStream errorStream = process.getErrorStream();
    int c = 0;
    while ((c = errorStream.read()) != -1) {
      System.out.print((char)c);
    }
  }
}

代码示例来源:origin: libgdx/libgdx

private void generateHFile (FileDescriptor file) throws Exception {
  String className = getFullyQualifiedClassName(file);
  String command = "javah -classpath " + classpath + " -o " + jniDir.path() + "/" + className + ".h " + className;
  Process process = Runtime.getRuntime().exec(command);
  process.waitFor();
  if (process.exitValue() != 0) {
    System.out.println();
    System.out.println("Command: " + command);
    InputStream errorStream = process.getErrorStream();
    int c = 0;
    while ((c = errorStream.read()) != -1) {
      System.out.print((char)c);
    }
  }
}

代码示例来源:origin: stanfordnlp/CoreNLP

public static InputStream getBZip2PipedInputStream(String filename) throws IOException {
 String bzcat = System.getProperty("bzcat", "bzcat");
 Runtime rt = Runtime.getRuntime();
 String cmd = bzcat + " " + filename;
 //log.info("getBZip2PipedInputStream: Running command: "+cmd);
 Process p = rt.exec(cmd);
 Writer errWriter = new BufferedWriter(new OutputStreamWriter(System.err));
 StreamGobbler errGobbler = new StreamGobbler(p.getErrorStream(), errWriter);
 errGobbler.start();
 return p.getInputStream();
}

代码示例来源:origin: apache/flink

private void startPython(String tmpPath, String args) throws IOException {
  String pythonBinaryPath = config.getString(PythonOptions.PYTHON_BINARY_PATH);
  try {
    Runtime.getRuntime().exec(pythonBinaryPath);
  } catch (IOException ignored) {
    throw new RuntimeException(pythonBinaryPath + " does not point to a valid python binary.");
  }
  process = Runtime.getRuntime().exec(pythonBinaryPath + " -B " + tmpPath + FLINK_PYTHON_PLAN_NAME + args);
  new Thread(new StreamPrinter(process.getInputStream())).start();
  new Thread(new StreamPrinter(process.getErrorStream())).start();
  server = new ServerSocket(0);
  server.setSoTimeout(50);
  process.getOutputStream().write("plan\n".getBytes(ConfigConstants.DEFAULT_CHARSET));
  process.getOutputStream().flush();
}

代码示例来源:origin: gocd/gocd

public static String exec(File workingDirectory, String... commands) {
  try {
    Process process = Runtime.getRuntime().exec(commands, null, workingDirectory);
    return captureOutput(process).toString();
  } catch (Exception e) {
    throw bomb(e);
  }
}

代码示例来源:origin: apache/rocketmq

public static void callShell(final String shellString, final InternalLogger log) {
  Process process = null;
  try {
    String[] cmdArray = splitShellString(shellString);
    process = Runtime.getRuntime().exec(cmdArray);
    process.waitFor();
    log.info("CallShell: <{}> OK", shellString);
  } catch (Throwable e) {
    log.error("CallShell: readLine IOException, {}", shellString, e);
  } finally {
    if (null != process)
      process.destroy();
  }
}

代码示例来源:origin: commons-io/commons-io

private void createCircularSymLink(final File file) throws IOException {
  if (!FilenameUtils.isSystemWindows()) {
    Runtime.getRuntime()
        .exec("ln -s " + file + "/.. " + file + "/cycle");
  } else {
    try {
      Runtime.getRuntime()
          .exec("mklink /D " + file + "/cycle" + file + "/.. ");
    } catch (final IOException ioe) { // So that tests run in FAT filesystems
      //don't fail
    }
  }
}

代码示例来源:origin: neo4j/neo4j

private boolean commandExists( String command )
{
  try
  {
    return Runtime.getRuntime().exec( command ).waitFor() == 0;
  }
  catch ( Throwable e )
  {
    return false;
  }
}
@Test

代码示例来源:origin: jenkinsci/jenkins

public OutputStream call() throws IOException {
  Process p = Runtime.getRuntime().exec(cmd,
    Util.mapToEnv(inherit(envOverrides)),
    workDir == null ? null : new File(workDir));
  List<String> cmdLines = Arrays.asList(cmd);
  new StreamCopyThread("stdin copier for remote agent on "+cmdLines,
    p.getInputStream(), out.getOut()).start();
  new StreamCopyThread("stderr copier for remote agent on "+cmdLines,
    p.getErrorStream(), err).start();
  // TODO: don't we need to join?
  return new RemoteOutputStream(p.getOutputStream());
}

代码示例来源:origin: commons-io/commons-io

private void setupSymlink(final File res, final File link) throws Exception {
  // create symlink
  final List<String> args = new ArrayList<>();
  args.add("ln");
  args.add("-s");
  args.add(res.getAbsolutePath());
  args.add(link.getAbsolutePath());
  Process proc;
  proc = Runtime.getRuntime().exec(args.toArray(new String[args.size()]));
  proc.waitFor();
}

代码示例来源:origin: commons-io/commons-io

private boolean chmod(final File file, final int mode, final boolean recurse)
    throws InterruptedException {
  // TODO: Refactor this to FileSystemUtils
  final List<String> args = new ArrayList<>();
  args.add("chmod");
  if (recurse) {
    args.add("-R");
  }
  args.add(Integer.toString(mode));
  args.add(file.getAbsolutePath());
  Process proc;
  try {
    proc = Runtime.getRuntime().exec(
        args.toArray(new String[args.size()]));
  } catch (final IOException e) {
    return false;
  }
  final int result = proc.waitFor();
  return result == 0;
}

代码示例来源:origin: apache/flink

private void killApplicationMaster(final String processName) throws IOException, InterruptedException {
  final Process exec = Runtime.getRuntime().exec("pkill -f " + processName);
  assertThat(exec.waitFor(), is(0));
}

代码示例来源:origin: neo4j/neo4j

public void doHeapDump( Pair<Long, String> pid ) throws Exception
{
  File outputFile = new File( outputDirectory, fileName( "heapdump", pid ) );
  log.info( "Creating heap dump of " + pid + " to " + outputFile.getAbsolutePath() );
  String[] cmdarray = new String[] {"jmap", "-dump:file=" + outputFile.getAbsolutePath(), "" + pid.first() };
  Runtime.getRuntime().exec( cmdarray ).waitFor();
}

代码示例来源:origin: neo4j/neo4j

public File doThreadDump( Pair<Long, String> pid ) throws Exception
{
  File outputFile = new File( outputDirectory, fileName( "threaddump", pid ) );
  log.info( "Creating thread dump of " + pid + " to " + outputFile.getAbsolutePath() );
  String[] cmdarray = new String[] {"jstack", "" + pid.first()};
  Process process = Runtime.getRuntime().exec( cmdarray );
  writeProcessOutputToFile( process, outputFile );
  return outputFile;
}

相关文章