Java代码中执行Linux命令,亲测可用

前提需要知道怎么在linux怎么新建java文件和怎么编译,否则请先学其他知识!!

import java.io.*;
public class Test{

public static void main(String[] args) throws Exception{
try{
Process process=Runtime.getRuntime().exec("ls ./");
InputStreamReader reader = new InputStreamReader(process.getInputStream());
LineNumberReader line = new LineNumberReader(reader);
String str;
while((str=line.readLine())!=null){
System.out.println(str);
}

}catch (Exception e){
e.printStackTrace();
}

System.out.println("done !!!");
}

2、可是有时候会用到特殊的linux命令的时候就有问题了,比如最近在写一个发送邮件的功能,通过linux下面的sendmail来发送邮件的时候,用上面的方法就不行了

  下面是使用linux发送邮件的命令全部步骤:

  

一、通过文件内容发送邮件

首先创建一个body.txt

1
[root@vps478753 ~]# touch body.txt

写入内容

1
[root@vps478753 ~]# echo 'This is test mail'>body.txt

发送邮件

1
[root@vps478753 ~]# mail -s 'Test mail' mail@lizhong.me < body.txt

不一会就收到邮件了

CentOS安装mail命令

点击打开,正文内容就是body.txt的内容

This is test mail

 

二、使用管道符【 | 】直接发送邮件内容

如果不想通过文件发送邮件内容也可以这么发送

1
[root@vps478753 ~]# echo "This is test mail" | mail -s 'Test mail' mail@lizhong.me

以上效果同文件发送邮件内容一样

如果提示mail: command not found

1
2
[root@vps478753 ~]# mail -s 'Test mail' mail@lizhong.me < body.txt
-bash: mail: command not found

那么就是没有安装mail命令,此时需要安装mail命令

1
[root@vps478753 ~]# yum install mailx -y

然后再重新发送以下邮件就好了!

-----以上内容纯属复制,原文地址:http://zdm2008.blog.163.com/blog/static/2049154520139795219380/

如果linux中有用到管道符的话需要这样写:

原文地址:https://www.cnblogs.com/ning-blogs/p/4682310.html