java如何调用Linux命令呢?

戚薇 Java经验 发布时间:2023-06-23 23:40:50 阅读数:8354 1
下文笔者讲述java代码调用linux命令的方法及示例
学习完本篇之后,你将掌握java代码操作linux的方法,如下所示
使用
 Runtime.getRuntime().exec("linux命令")
即可运行linux命令
例:Java运行Linux命令的示例
package com.java265;
 
import java.io.IOException;  
public class TestLinuxCmd {
  
	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();
		}
	} 
}

//使用Runtime调用命令并获得结果

package com.java265; 
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
  
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();
		}
	}
}
版权声明

本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。

本文链接: https://www.Java265.com/JavaJingYan/202306/16875348856874.html

最近发表

热门文章

好文推荐

Java265.com

https://www.java265.com

站长统计|粤ICP备14097017号-3

Powered By Java265.com信息维护小组

使用手机扫描二维码

关注我们看更多资讯

java爱好者