Java调用Linux命令(cd的处理)
一、Java调用Linux系统的命令非常简单
这是一个非常常用的调用方法示例:
public String executeLinuxCmd(String cmd) {
System.out.println("got cmd job : " + cmd);
Runtime run = Runtime.getRuntime();
try {
Process process = run.exec(cmd);
InputStream in = process.getInputStream();
BufferedReader bs = new BufferedReader(new InputStreamReader(in));
// System.out.println("[check] now size \n"+bs.readLine());
StringBuffer out = new StringBuffer();
byte[] b = new byte[8192];
for (int n; (n = in.read(b)) != -1;) {
out.append(new String(b, 0, n));
}
System.out.println("job result [" + out.toString() + "]");
in.close();
// process.waitFor();
process.destroy();
return result;
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
二、含有管道符(|)多级命令串联查询
public List<String> executeLinuxCmd(String cmd) {
System.out.println("got cmd job : " + cmd);
Runtime run = Runtime.getRuntime();
try {
// Process process = run.exec(cmd);
Process process = run.exec(new String[] {"/bin/sh", "-c", cmd});
InputStream in = process.getInputStream();
BufferedReader bs = new BufferedReader(new InputStreamReader(in));
List<String> list = new ArrayList<String>();
String result = null;
while ((result = bs.readLine()) != null) {
System.out.println("job result [" + result + "]");
list.add(result);
}
in.close();
// process.waitFor();
process.destroy();
return list;
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
三、含有cd操作的方法示例
1. 问题背景
1.1 java程序运行在/home/lings目录下;
1.2 希望删除/home/test目录下的文件proxy.log;
1.3 调用上面的接口两次?
executeLinuxCmd("cd /home/test");
executeLinuxCmd("rm -fr /home/proxy.log");
是不行的!
1.4 这个接口的调用是单次事务型的,就是每次调用都是独立的事务或者说操作,没有关联的。
那这种“复杂”一点的操作流程怎么办呢?
1.5 方法a: 可以写一个独立的脚本,然后一次运行脚本,这样多复杂的逻辑都没问题。
1.6 方法b: 可以启动一个shell长连接,保持连接,发送多条命令,最后释放连接。
示例逻辑代码:
public void executeNewFlow() {
Runtime run = Runtime.getRuntime();
File wd = new File("/bin");
System.out.println(wd);
Process proc = null;
try {
proc = run.exec("/bin/bash", null, wd);
} catch (IOException e) {
e.printStackTrace();
}
if (proc != null) {
BufferedReader in = new BufferedReader(new InputStreamReader(proc.getInputStream()));
PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(proc.getOutputStream())), true);
out.println("cd /home/test");
out.println("pwd");
out.println("rm -fr /home/proxy.log");
out.println("exit");//这个命令必须执行,否则in流不结束。
try {
String line;
while ((line = in.readLine()) != null) {
System.out.println(line);
}
proc.waitFor();
in.close();
out.close();
proc.destroy();
} catch (Exception e) {
e.printStackTrace();
}
}
}
三的优化和演进(返回值)
public List<String> executeNewFlow(List<String> commands) {
List<String> rspList = new ArrayList<String>();
Runtime run = Runtime.getRuntime();
try {
Process proc = run.exec("/bin/bash", null, null);
BufferedReader in = new BufferedReader(new InputStreamReader(proc.getInputStream()));
PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(proc.getOutputStream())), true);
for (String line : commands) {
out.println(line);
}
// out.println("cd /home/test");
// out.println("pwd");
// out.println("rm -fr /home/proxy.log");
out.println("exit");// 这个命令必须执行,否则in流不结束。
String rspLine = "";
while ((rspLine = in.readLine()) != null) {
System.out.println(rspLine);
rspList.add(rspLine);
}
proc.waitFor();
in.close();
out.close();
proc.destroy();
} catch (IOException e1) {
e1.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
return rspList;
}
Java调用Linux命令(cd的处理)的更多相关文章
- Java调用Linux命令执行
调用方式 Java调用linux命令执行的方式有两种,一种是直接调用linux命令,一种是将linux命令写到.sh脚本中,然后调用脚本执行. 详细说明 直接调用:使用java中lang包下面的Run ...
- java调用Linux命令报错:java.io.IOException: Cannot run program "ps": CreateProcess error=2, ?????????
在idea里面,java代码:Runtime.getRuntime().exec("ps -aux") 是因为默认是用windows平台运行了,所以报错,得改成调用Linux平台运 ...
- java 调用 linux 命令行 +使用管道、awk等命令进行数据处理的方法
这里用 sh -c "命令" 的方式是因为java里只能这么用,管道这边java处理不了,所以只能一次执行一条命令,但是在linux里用 sh -c 的方式返回的awk处理过的结果 ...
- Java调用Linux命令
// int tp = 1 返回执行结果 非1 返回命令执行后的输出 public static String runCommand(String cmd, int tp) { StringBuff ...
- java调用Linux执行Python爬虫,并将数据存储到elasticsearch--(环境脚本搭建)
java调用Linux执行Python爬虫,并将数据存储到elasticsearch中 一.以下博客代码使用的开发工具及环境如下: 1.idea: 2.jdk:1.8 3.elasticsearch: ...
- java基础/java调用shell命令和脚本
一.项目需求: 从某一机构获取证书,证书机构提供小工具,执行.sh脚本即可启动服务,本地调用该服务即可获取证书. 问题:linux服务器启动该服务,不能关闭.一旦关闭,服务即停止. 解决方案:java ...
- php通过system()调用Linux命令问题
最近在做php和linux crontab的联调,发现php在linux下的权限问题需要引起注意,调试问题的过程中发现有许多问题前人说的比较零散,我在这里汇总,顺带抛砖引玉一下. 1.$result= ...
- scala调用Linux命令行
在 scala 里面存在 调用 Linux 命令行的函数: import scala.sys.process._ 执行的方法也不难: import scala.sys.process._ /** * ...
- Java调用windows命令
JAVA调用windows的cmd命令 用起来会让程序变得更加简洁明了,非常实用. 核心就是使用 Runtime类. cmd的xcopy就有很强大的文件夹,文件处理功能. 下面就以xcopy来说明,如 ...
随机推荐
- MongoDB Sort op eration used more than the maximum 33554432 bytes of RAM. Add an index, or speci fy a smaller limit.
最近在获取mongodb某个集合的数据过程中,在进行排序的过程中报错,具体报错信息如下: Error: error: { , "errmsg" : "Executor e ...
- [Backbone]4. Model & View, toggle between Model and View. -- 1
如上图所示: Server有Data都交给Models处理, 然后由Models给Views Data,让View去告诉DOM如何显示, 然后DOM显示HTML; View events update ...
- Roo中的@Version
首页 关于 Roo中的@Version 发表回复 问题提出 当我们为entity添加@RooJpaActiveRecord注解时,Roo为我们自动生成了一个名为Entity_Roo_Jpa_Entit ...
- C#.NET常见问题(FAQ)-abstract抽象类如何理解
例如有太多相似,但是不一样的类,他们都继承自同一个基类(比如大型游戏有各个种族,每个种族有各种人物,加起来几百种类型,然后基本上他们都是一个角色,都有基本相同的属性和方法,比如都会走,只是速度不同,都 ...
- uni-app - Class 与 Style 绑定
参考uni文档:https://uniapp.dcloud.io/use?id=class-%E4%B8%8E-style-%E7%BB%91%E5%AE%9A 参考vue文档:https://cn. ...
- VB总结1-事件过程之键盘鼠标过程
事件过程:参考 (http://baike.baidu.com/view/1523990.htm) 事件是指对象对于外部动作的响应,当对象发生了某个事件,就会执行与此对象的这个事件相应的代码,这段代码 ...
- MySQL主从常见的架构
Master-Slave 级联 双Master互为主备
- 解决openssh TimeOut
SSH Client:ServerAliveInterval 100 SSH server:ClientAliveInterval 30TCPKeepAlive yes ClientAliveCoun ...
- 在命令行上 使用 mutt, fetchmail, maildrop, msmtp 收发邮件
基于shell 现在已经有了 Mail.app, Thunderbird, Outlook 这些图形化工具能很方便的处理邮件,为啥还需要 mutt 这种命令行文本方式的邮件工具呢?mutt 的一个优势 ...
- 编译时:virtual memory exhausted: Cannot allocate memory(转)
一.问题 当安装虚拟机时系统时没有设置swap大小或设置内存太小,编译程序会出现virtual memory exhausted: Cannot allocate memory的问题,可以用swap扩 ...