Java exec exec(String program, String... args)

Here you can find the source of exec(String program, String... args)

Description

exec

License

Apache License

Declaration

public static Process exec(String program, String... args) 

Method Source Code


//package com.java2s;
/*//from  w ww.ja  v  a2 s  .  com
 * Copyright 2014-2015 ieclipse.cn.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

public class Main {
    public static Process exec(String program, List<String> args) {
        ProcessBuilder builder = new ProcessBuilder();
        File f = new File(program);
        if (f != null && f.getParentFile() != null && f.getParentFile().exists()) {
            builder.directory(f.getParentFile());
        }

        String cmd = String.format("\"%s\"", f.getName());
        // String cmd = f.getName();
        if (args != null) {
            args.add(0, cmd);
            builder.command(args);
        } else {
            builder.command(cmd);
        }
        System.out.println(builder.command());
        try {
            Process p = builder.start();
            return p;
        } catch (IOException e) {
            e.printStackTrace();
            try {
                System.out.println(new String(e.toString().getBytes("utf-8"), "gbk"));
            } catch (UnsupportedEncodingException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }
            return null;
        }
    }

    public static Process exec(String program, String... args) {
        if (args != null) {
            List<String> array = new ArrayList<String>(args.length);
            for (int i = 0; i < args.length; i++) {
                array.add(args[i]);
            }
            return exec(program, array);
        }
        return exec(program, (List<String>) null);
    }

    public static Process exec(String program) {
        return exec(program, (List<String>) null);
    }
}

Related

  1. exec(String command)
  2. exec(String command, String workingDir)
  3. exec(String command, String[] args_, String[] environment)
  4. exec(String command[], boolean stop)
  5. exec(String exec)
  6. exec(String pwd, boolean quiet, String... command)
  7. exec(String... _command)
  8. exec(String... args)
  9. exec(String... cmd)