UNIX下用Java 代码调用一个shell command 并取得执行结果

本文提供两个Java示例程序,展示如何通过Java执行系统命令并读取命令的输出和错误信息。第一个示例演示了如何执行df -k命令来获取磁盘使用情况,第二个示例则展示了如何执行ls > fred.txt命令并将输出重定向到文件。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 

public class Test {
	
	public static void main(String[] args) throws Exception {
		try {
			//execute shell command: df -k .
			Process fileSystemDfInfo = Runtime.getRuntime().exec("df -k .");

			BufferedReader reader = new BufferedReader(
					new InputStreamReader(fileSystemDfInfo.getInputStream()));			
			String contentLine;
			while ((contentLine = reader.readLine()) != null){
				//do something with contentLine
				System.out.println(contentLine);
			}
			reader.close();
		} catch(Exception e) {
			e.printStackTrace();
		}
	}

}
 

 

===

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

public class RunSystemCommand {
	public static void main(String args[]) {
		String s = null;
		// system command to run
		String cmd = "ls > fred.txt";
		// set the working directory for the OS command processor
		File workDir = new File("/dir1/dir2");

		try {
			Process p = Runtime.getRuntime().exec(cmd, null, workDir);
			int i = p.waitFor();
			if (i == 0) {
				BufferedReader stdInput = new BufferedReader(
						new InputStreamReader(p.getInputStream()));
				// read the output from the command
				while ((s = stdInput.readLine()) != null) {
					System.out.println(s);
				}
			} else {
				BufferedReader stdErr = new BufferedReader(
						new InputStreamReader(p.getErrorStream()));
				// read the output from the command
				while ((s = stdErr.readLine()) != null) {
					System.out.println(s);
				}

			}
		} catch (Exception e) {
			System.out.println(e);
		}
	}
}

 

Resource: 1. http://bjyzxxds.iteye.com/blog/460126

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值