本文主要想说明:在开发过程中,要善于利用JAVA面向对象编程的优势,与Linux/Unix Shell命令的优势,并将二者相结合。
JAVA代码:
package shuai.study.cmd; import java.io.IOException; import java.io.InputStream; import java.util.Iterator; import java.util.List; import org.apache.commons.io.IOUtils; public class TestCmd { public static InputStream executeCmd(String cmd) { String[] cmdArray = new String[] { "bash", "-c", cmd }; Runtime runtime = Runtime.getRuntime(); Process process = null; try { process = runtime.exec(cmdArray); } catch (IOException e) { e.printStackTrace(); } return process.getInputStream(); } public static void readInputStream(InputStream inputStream) { try { List<String> list = IOUtils.readLines(inputStream); Iterator<String> iterator = list.iterator(); while (iterator.hasNext()) { String line = iterator.next(); System.out.println(line); } } catch (IOException e) { e.printStackTrace(); } finally { IOUtils.closeQuietly(inputStream); } } public static void main(String[] args) { String cmd = "awk -F':' '{print $NF}' /etc/passwd"; if (args != null && args.length > 0) { cmd = args[0]; } InputStream inputStream = TestCmd.executeCmd(cmd); TestCmd.readInputStream(inputStream); } }
运行脚本run.sh:
#!/bin/bash java -Djava.ext.dirs=../lib -Xverify:none -Xms1024m -Xmx2048m -Xmn512m -XX:PermSize=96m -XX:MaxPermSize=96m -XX:+DisableExplicitGC -Xnoclassgc -XX:+UseParNewGC -XX:+UseConcMarkSweepGC -XX:CMSInitiatingOccupancyFraction=85 shuai.study.cmd.TestCmd "$*"
安装包java-cmd.zip:java-cmd.zip
时间: 2024-11-02 07:58:14