java.lang.ProcessBuilder.directory()方法的使用及代码示例

x33g5p2x  于2022-01-25 转载在 其他  
字(8.7k)|赞(0)|评价(0)|浏览(142)

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

ProcessBuilder.directory介绍

[英]Returns the working directory of this process builder. If null is returned, then the working directory of the Java process is used when a process is started.
[中]返回此process builder的工作目录。如果返回null,则在启动进程时使用Java进程的工作目录。

代码示例

代码示例来源:origin: SonarSource/sonarqube

/**
 * @see java.lang.ProcessBuilder#directory(File)
 */
@Override
public ProcessBuilder directory(File dir) {
 builder.directory(dir);
 return this;
}

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

public ProcessRunner withWorkingDir(String directory) {
  builder.directory(new File(directory));
  return this;
}

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

ProcessBuilder pb = new ProcessBuilder("myshellScript.sh", "myArg1", "myArg2");
Map<String, String> env = pb.environment();
env.put("VAR1", "myValue");
env.remove("OTHERVAR");
env.put("VAR2", env.get("VAR1") + "suffix");
pb.directory(new File("myDir"));
Process p = pb.start();

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

Process p = null;
ProcessBuilder pb = new ProcessBuilder("do_foo.sh");
pb.directory("/home");
p = pb.start();

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

ProcessBuilder pb = new ProcessBuilder("command", "argument");
pb.directory(new File(<directory from where you want to run the command>));
pb.inheritIO();
Process p = pb.start();
p.waitFor();

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

public Process exec(String[] cmdarray, String[] envp, File dir)
  throws IOException {
  return new ProcessBuilder(cmdarray)
    .environment(envp)
    .directory(dir)
    .start();
}

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

private static boolean startProcess (String[] commands, File directory, final CharCallback callback) {
    try {
      final Process process = new ProcessBuilder(commands).redirectErrorStream(true).directory(directory).start();

      Thread t = new Thread(new Runnable() {
        @Override
        public void run () {
          BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()), 1);
          try {
            int c = 0;
            while ((c = reader.read()) != -1) {
              callback.character((char)c);						
            }
          } catch (IOException e) {
//                        e.printStackTrace();
          }
        }
      });
      t.setDaemon(true);
      t.start();
      process.waitFor();
      t.interrupt();
      return process.exitValue() == 0;
    } catch (Exception e) {
      e.printStackTrace();
      return false;
    }
  }
}

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

ProcessBuilder pb = new ProcessBuilder(
  "C:/Program Files/WinRAR/winrar",
  "x",
  "myjar.jar",
  "*.*",
  "new");
pb.directory(new File("H:/"));
pb. redirectErrorStream(true);

Process p = pb.start();

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

ProcessBuilder pb = new ProcessBuilder("/path/to/java", "-jar", "your.jar");
pb.directory(new File("preferred/working/directory"));
Process p = pb.start();

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

public int run() throws IOException, InterruptedException {
    File workingDir = builder.directory() == null ? new File(".") : builder.directory();
    System.out.println(String.format("Trying to run command: %s from %s", Arrays.toString(builder.command().toArray()), workingDir.getAbsolutePath()));
    Process process = builder.start();
    int exitCode = process.waitFor();
    System.out.println("Finished command: " + Arrays.toString(builder.command().toArray()) + ". Exit code: " + exitCode);
    if (exitCode != 0) {
      if (failOnError) {
        throw new RuntimeException(String.format("Command exited with code %s. \n Exception: %s", exitCode, IOUtils.toString(process.getErrorStream())));
      } else {
        LOGGER.error("Command exited with code {}. \n Exception: {}", exitCode, IOUtils.toString(process.getErrorStream()));
      }
    }
    return exitCode;
  }
}

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

ProcessBuilder pb = new ProcessBuilder("myCommand", "myArg1", "myArg2");
Map<String, String> env = pb.environment();
env.put("VAR1", "myValue");
env.remove("OTHERVAR");
env.put("VAR2", env.get("VAR1") + "suffix");
pb.directory(new File("myDir"));
Process p = pb.start();

代码示例来源:origin: Tencent/tinker

public static void exec(ArrayList<String> args, File path) throws RuntimeException, IOException, InterruptedException {
  ProcessBuilder ps = new ProcessBuilder(args);
  ps.redirectErrorStream(true);
  if (path != null) {
    ps.directory(path);
  }
  Process pr = ps.start();
  BufferedReader ins = null;
  try {
    ins = new BufferedReader(new InputStreamReader(pr.getInputStream()));
    String line;
    while ((line = ins.readLine()) != null) {
      System.out.println(line);
    }
    if (pr.waitFor() != 0) {
      throw new RuntimeException("exec cmd failed! args: " + args);
    }
  } finally {
    try {
      pr.destroy();
    } catch (Throwable ignored) {
      // Ignored.
    }
    StreamUtil.closeQuietly(ins);
  }
}

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

/**
 * Set the working directory of the target process.
 *
 * @param directory the directory (must not be {@code null})
 * @return this builder
 */
public Builder setWorkingDirectory(File directory) {
  checkNotNullParam("directory", directory);
  builderProcessor = builderProcessor.andThen(pb -> pb.directory(directory));
  return this;
}

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

public Channel launchChannel(String[] cmd, OutputStream out, FilePath workDir, Map<String,String> envVars) throws IOException {
  printCommandLine(cmd, workDir);
  ProcessBuilder pb = new ProcessBuilder(cmd);
  pb.directory(toFile(workDir));
  if (envVars!=null) pb.environment().putAll(envVars);
  return launchChannel(out, pb);
}

代码示例来源:origin: soabase/exhibitor

private ProcessBuilder buildZkServerScript(String operation) throws IOException
{
  Details         details = new Details(exhibitor);
  File            binDirectory = new File(details.zooKeeperDirectory, "bin");
  File            zkServerScript = new File(binDirectory, "zkServer.sh");
  return new ProcessBuilder(zkServerScript.getAbsolutePath(), operation).directory(binDirectory.getParentFile());
}

代码示例来源:origin: KronicDeth/intellij-elixir

@NotNull
protected Process startProcess(@NotNull List<String> commands) throws IOException {
  ProcessBuilder builder = new ProcessBuilder(commands);
  setupEnvironment(builder.environment());
  builder.directory(myWorkDirectory);
  builder.redirectErrorStream(false);
  return builder.start();
}

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

public ProcessWrapper createProcess(String[] commandLine, String commandLineForDisplay, File workingDir, Map<String, String> envMap, EnvironmentVariableContext environmentVariableContext,
                  ConsoleOutputStreamConsumer consumer, String processTag, String encoding, String errorPrefix) {
  ProcessBuilder processBuilder = new ProcessBuilder(commandLine);
  LOG.debug("Executing: {}", commandLineForDisplay);
  if (workingDir != null) {
    LOG.debug("[Command Line] Using working directory {} to start the process.", workingDir.getAbsolutePath());
    processBuilder.directory(workingDir);
  }
  processBuilder.environment().putAll(environmentVariableContext.getProperties());
  processBuilder.environment().putAll(envMap);
  Process process = startProcess(processBuilder, commandLineForDisplay);
  ProcessWrapper processWrapper = new ProcessWrapper(process, processTag, commandLineForDisplay, consumer, encoding, errorPrefix);
  processMap.putIfAbsent(process, processWrapper);
  return processWrapper;
}

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

public void runCharniak(int n, String infile, String outfile, String errfile) {
 try {
  if (n == 1) n++;  // Charniak does not output score if n = 1?
  List<String> args = new ArrayList<>();
  args.add(parserExecutable);
  args.add(infile);
  ProcessBuilder process = new ProcessBuilder(args);
  process.directory(new File(this.dir));
  PrintWriter out = IOUtils.getPrintWriter(outfile);
  PrintWriter err = IOUtils.getPrintWriter(errfile);
  SystemUtils.run(process, out, err);
  out.close();
  err.close();
 } catch (IOException ex) {
  throw new RuntimeException(ex);
 }
}

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

/**
 * @param err
 *      null to redirect stderr to stdout.
 */
public LocalProc(String[] cmd,String[] env,InputStream in,OutputStream out,OutputStream err,File workDir) throws IOException {
  this( calcName(cmd),
     stderr(environment(new ProcessBuilder(cmd),env).directory(workDir), err==null || err== SELFPUMP_OUTPUT),
     in, out, err );
}

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

public Number launch(Map<String, Object> conf, TopologyContext context, boolean changeDirectory) {
  ProcessBuilder builder = new ProcessBuilder(command);
  if (!env.isEmpty()) {
    Map<String, String> buildEnv = builder.environment();
    modifyEnvironment(buildEnv);
  }
  if (changeDirectory) {
    builder.directory(new File(context.getCodeDir()));
  }
  ShellLogger = LoggerFactory.getLogger(context.getThisComponentId());
  this.componentName = context.getThisComponentId();
  this.serializer = getSerializer(conf);
  try {
    _subprocess = builder.start();
    processErrorStream = _subprocess.getErrorStream();
    serializer.initialize(_subprocess.getOutputStream(), _subprocess.getInputStream());
    this.pid = serializer.connect(conf, context);
  } catch (IOException e) {
    throw new RuntimeException(
      "Error when launching multilang subprocess\n"
      + getErrorsString(), e);
  } catch (NoOutputException e) {
    throw new RuntimeException(e + getErrorsString() + "\n");
  }
  return this.pid;
}

相关文章