在Java代码中运行jar包或者执行shell指令

2 篇文章 0 订阅
2 篇文章 0 订阅

今日突发奇想,想在Java代码中执行hadoop命令如:

“hadoop fs -ls /”

于是查了一下,发现可以利用Java的Runtime来完成上面功能,具体代码如下:

public static void main(String[] args) {
	try {
		Process ps = Runtime.getRuntime().exec("/home/hadoop/hadoop/hadoop-1.2.1/bin/hadoop jar /home/hadoop/mahout/mahout-distribution-0.9/mahout-core-0.9-job.jar org.apache.mahout.fpm.pfpgrowth.FPGrowthDriver -i /user/hadoop/testdata/history_download -o out/ -k 3 -method mapreduce -regex '[\\t]' -s 10");<span style="white-space:pre">		</span>System.out.println(loadInputStream(ps.getInputStream()));
		System.out.println(loadInputStream(ps.getErrorStream()));
	} catch (IOException e) {
		e.printStackTrace();
	}
}

private static String loadInputStream(InputStream is) throws IOException {
	int ptr = 0;
	BufferedInputStream bis = new BufferedInputStream(is);
	StringBuffer sb = new StringBuffer();
	while ((ptr = bis.read()) != -1) {
		sb.append((char)ptr);
	}
	return sb.toString();
}
其中,用到了一下命令执行代码,代码中命令的路径最好是完整的路径,不然可能会报找不到路径错误,执行后会产生命令执行的输出。
Runtime.getRuntime().exec()


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值