java1996 2017-01-08 02:35 采纳率: 0%
浏览 886

实现了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条回答 默认 最新

  • threenewbee 2017-01-08 02:38
    关注

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

    评论

报告相同问题?

悬赏问题

  • ¥15 数值计算均差系数编程
  • ¥15 redis-full-check比较 两个集群的数据出错
  • ¥15 Matlab编程问题
  • ¥15 训练的多模态特征融合模型准确度很低怎么办
  • ¥15 kylin启动报错log4j类冲突
  • ¥15 超声波模块测距控制点灯,灯的闪烁很不稳定,经过调试发现测的距离偏大
  • ¥15 import arcpy出现importing _arcgisscripting 找不到相关程序
  • ¥15 onvif+openssl,vs2022编译openssl64
  • ¥15 iOS 自定义输入法-第三方输入法
  • ¥15 很想要一个很好的答案或提示