java如何调用Linux命令呢?
下文笔者讲述java代码调用linux命令的方法及示例
学习完本篇之后,你将掌握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(); } } }
版权声明
本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。