2 java1996 java1996 于 2017.01.08 10:35 提问

实现了java exec 调用 .bat,能否为此代码添加注释,本人初学看不懂

package spider.scrapyd;

import java.io.BufferedReader;
import java.io.File;
import java.io.InputStreamReader;

public class Command {

public static String exec(String[] cmd, File path) {

    final StringBuffer stringBuffer = new StringBuffer();
    try {
        final Process process = Runtime.getRuntime().exec(cmd, null, path);
        new Thread(new Runnable() {
            public void run() {
                try {
                    BufferedReader reader = new BufferedReader(
                            new InputStreamReader(process.getInputStream()));
                    String line = null;
                    while ((line = reader.readLine()) != null) {
                        stringBuffer.append(line);
                    }
                    reader.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();
        new Thread(new Runnable() {
            public void run() {
                try {
                    BufferedReader reader = new BufferedReader(
                            new InputStreamReader(process.getErrorStream()));
                    String line = null;
                    while ((line = reader.readLine()) != null) {
                        stringBuffer.append(line);
                    }
                    reader.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();
        process.getOutputStream().close();
        process.waitFor();
        if (process.exitValue() == 0) {
            System.out.println("successfully execute command");
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    String str = stringBuffer.toString();
    System.out.println(str);
    return str ;
}

public static void main(String[] args) {
//  String[] cmd = new String[] { "cmd", "/c", "wmic cpu get name" };
    String[] cmd = new String[] { "cmd", "/c", "scrapyd-deploy -p hrtencent -v r1.0.0 " };
    File f = new File("F:\\pywork\\PycharmProjects\\TencentHR\\hrtencent");
    String str = exec(cmd,f);
    System.out.println(str);
}

}

1个回答

caozhy
caozhy   Ds   Rxr 2017.01.08 10:38

exec实现的功能是调用一个命令行程序,然后等待它运行结束,将输出的信息作为返回值返回主程序,之所以写那么多,就是实现等待和返回输出。如果你不理解,当成一个黑盒看待就好了。
scrapyd-deploy的功能你可以在命令行直接输入 scrapyd-deploy -h 看

Csdn user default icon
上传中...
上传图片
插入图片
准确详细的回答,更有利于被提问者采纳,从而获得C币。复制、灌水、广告等回答会被删除,是时候展现真正的技术了!