zl程序教程

您现在的位置是:首页 >  后端

当前栏目

JavaDemo——java调用Linux命令

JAVALinux命令 调用 JavaDemo
2023-09-11 14:16:28 时间

Demo:

/**
 * createtime : 2018年9月6日 下午5:14:20
 */
package com.useLinuxCmd;

import java.io.IOException;

/**
 * TODO
 * @author XWF
 */
public class TestLinuxCmd {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		 Process proc = null;
		try {
			//创建文件
			String touchCmd = "touch hello.txt";
			proc = Runtime.getRuntime().exec(touchCmd);
			proc.waitFor(); //阻塞,直到上述命令执行完
			
			//管道类命令要用这种方式
			String[] cmds = {"/bin/sh","-c","echo helloworld > hello.txt"};
			proc = Runtime.getRuntime().exec(cmds);
			proc.waitFor(); //阻塞,直到上述命令执行完
			
			//删除文件
			String rmCmd = "rm -rf needrm.txt";
			proc = Runtime.getRuntime().exec(rmCmd);
			proc.waitFor(); //阻塞,直到上述命令执行完
			
			//执行文件
			String bashCmd = "bash mkfolder.sh";
			proc = Runtime.getRuntime().exec(bashCmd);
			proc.waitFor(); //阻塞,直到上述命令执行完
		} catch (InterruptedException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

}

mkfolder.sh脚本:

#!/bin/sh
mkdir myfolder

 把java代码生成jar包,放到linux系统上运行。

结果:

2021.12.20添加

通过Runtime调用命令并获得结果:

/**
 * 2021年12月20日下午3:48:23
 */
package testRunCmd;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

/**
 * @author XWF
 *
 */
public class TestRunCmd {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		try {
			String cmd = "ls -ahl";
			
			String line = null;
			StringBuilder sb = new StringBuilder();
			Runtime runtime = Runtime.getRuntime();
			Process proc = runtime.exec(new String[] {"/bin/sh", "-c", cmd});
			BufferedReader br = new BufferedReader(new InputStreamReader(proc.getInputStream()));
			while((line = br.readLine()) != null) {
				sb.append(line + "\n");
			}
			String result = sb.toString();
			
			System.out.println("执行结果:" + result);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

}

放到linux上运行结果: