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中有用到管道符的話需要這樣寫:


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM