导航:首页 > 程序命令 > java调用linux命令

java调用linux命令

发布时间:2022-05-01 22:47:53

1. java调用linux终端命令,如何使终端不直接退出

#include "stdio.h"
#include "conio.h"
main()
{
int i,j,result;
printf("\n");
for (i=1;i<10;i++)
{
for(j=1;j<10;j++)
{
result=i*j;
printf("%d*%d=%-3d",i,j,result); /*-3d表示左对齐,占3位*/
}
printf("\n"); /*每一行后换行*/
}
getch();
}

2. java怎么调用linux的命令怎么输入一条命令让linux用终端运行,然后获得返回的文本

用java的process类了。
process这个类是一个抽象类,封装了一个进程(你在调用linux的命令或者shell脚本就是为了执行一个在linux下执行的程序,所以应该使用process类)。
process类提供了执行从进程输入,执行输出到进程,等待进程完成,检查进程的推出状态,以及shut down掉进程。

3. 如何用java调用linux shell命令

代码方法如下:
public static ArrayList<String> command(final String cmdline,
final String directory) {
try {
Process process =
new ProcessBuilder(new String[] {"bash", "-c", cmdline})
.redirectErrorStream(true)
.directory(new File(directory))
.start();

ArrayList<String> output = new ArrayList<String>();
BufferedReader br = new BufferedReader(
new InputStreamReader(process.getInputStream()));
String line = null;
while ( (line = br.readLine()) != null )
output.add(line);

//There should really be a timeout here.
if (0 != process.waitFor())
return null;

return output;

} catch (Exception e) {
// 处理异常
}
}

4. java怎么执行linux交互式命令

Process prc = runtime.exec(.....); prc.waitFor();//这行就能阻塞后续代码的执行,直到你执行的命令结束。

5. java程序里调用linux命令

1.Java调用shell

Java语言以其跨平台性和简易性而着称,在Java里面的lang包里(java.lang.Runtime)提供了一个允许Java程序与该程序所运
行的环境交互的接口,这就是Runtime类,在Runtime类里提供了获取当前运行环境的接口。
其中的exec函数返回一个执行shell命令的子进程。exec函数的具体实现形式有以下几种:
public Process exec(String command) throws IOException
public Process exec(String command,String[] envp) throws
IOException
public Process exec(String command,String[] envp,File dir) throws
IOException
public Process exec(String[] cmdarray) throws IOException
public Process exec(String[] cmdarray, String[] envp) throws
IOException
public Process exec(String[] cmdarray, String[] envp,File dir)
throws IOException

我们在这里主要用到的是第一个和第四个函数,具体方法很简单,就是在exec函数中传递一个代表命令的字符串。exec函数返回的是一个Process类
型的类的实例。Process类主要用来控制进程,获取进程信息等作用。(具体信息及其用法请参看Java doc)。

1)执行简单的命令的方法:

代码如下:

6. java中如何执行linux命令

执行linux命令基,基本思路是从控制台获得输入的指令,启动命令行执行命令,捕捉异常,示例如下:

publicclassTestRunTime{

publicstaticvoidmain(String[]args)throwsIOException,InterruptedException{
Stringcmd="";

if(args==null||args.length==0){
System.out.println("请输入命令行参数");
}else{

for(inti=0;i<args.length;i++){//获得输入的命令
cmd+=args[i]+"";
}
}


try{
Processprocess=Runtime.getRuntime().exec(cmd);//执行命令

InputStreamReaderir=newInputStreamReader(process.getInputStream());
LineNumberReaderinput=newLineNumberReader(ir);

Stringline;
while((line=input.readLine())!=null){//输出结果
System.out.println(line);
}
}catch(java.io.IOExceptione){
System.err.println("IOException"+e.getMessage());//捕捉异常
}
}
}

7. java如何调用Linux下的top命令

Runtime.getRuntime().exec("top -n 1>text.txt");


test.sh:
#!/bin/bash
top -n 1>test.txt

Runtime.getRuntime().exec("test.sh");
Runtime.getRuntime().exec("bash test.sh");

多试试,肯定是这样调用的,只有这个方法是调用本地进程的。

8. 如何在java程序中调用linux命令或者shell脚本

在java程序中如何调用linux的命令?如何调用shell脚本呢?

这里不得不提到java的process类了。

process这个类是一个抽象类,封装了一个进程(你在调用linux的命令或者shell脚本就是为了执行一个在linux下执行的程序,所以应该使用process类)。

process类提供了执行从进程输入,执行输出到进程,等待进程完成,检查进程的推出状态,以及shut down掉进程。

至于详细的process类的介绍放在以后介绍。

另外还要注意一个类:Runtime类,Runtime类是一个与JVM运行时环境有关的类,这个类是Singleton的。

这里用到的Runtime.getRuntime()方法是取得当前JVM的运行环境,也是java中唯一可以得到运行环境的方法。(另外,Runtime的大部分方法都是实例方法,也就是说每次运行调用的时候都需要调用到getRuntime方法)

下面说说Runtime的exec()方法,这里要注意的有一点,就是public Process exec(String [] cmdArray, String [] envp);这个方法中cmdArray是一个执行的命令和参数的字符串数组,数组的第一个元素是要执行的命令往后依次都是命令的参数,envp感觉应该和C中的execve中的环境变量是一样的,envp中使用的是name=value的方式。

下面说一下,如何使用process来调用shell脚本

例如,我需要在linux下实行linux命令:sh test.sh,下面就是执行test.sh命令的方法:

这个var参数就是日期这个201102包的名字。

String shpath="/test/test.sh"; //程序路径

Process process =null;

String command1 = “chmod 777 ” + shpath;
process = Runtime.getRuntime().exec(command1);
process.waitFor();

String var="201102"; //参数

String command2 = “/bin/sh ” + shpath + ” ” + var;
Runtime.getRuntime().exec(command2).waitFor();

注意:

1

我为什么要使用 chmod 777命令呢?在有的机器上面,可能没有设置权限问题。这是你在linux下面执行shell脚本需要注意的问题。没有的话,就需要添加权限,就用chmod 777,否则在执行到Runtime.getRuntime().exec的时侯会出现Permission denied错误。

2

waitFor()这个也是必不可缺的,如果你需要执行多行命令的话,把waitFor()这个加上。

9. 怎么用java代码运行linux命令

以下方法支持Linux和windows两个系统的命令行调用。还用到了apache的lang工具包commons-lang3-3.1.jar来判断操作系统类型、也用到了和log4j-1.2.16.jar来打印日志。至于rm -rf 是否能成功删除文件,可以手动去调用命令行试试。

privateStringcallCmd(Stringcmd)throwsInterruptedException,UnHandledOSException,ExecuteException{
if(SystemUtils.IS_OS_LINUX){
try{
//使用Runtime来执行command,生成Process对象
Processprocess=Runtime.getRuntime().exec(
newString[]{"/bin/sh","-c",cmd});
intexitCode=process.waitFor();
//取得命令结果的输出流
InputStreamis=process.getInputStream();
//用一个读输出流类去读
InputStreamReaderisr=newInputStreamReader(is);
//用缓冲器读行
BufferedReaderbr=newBufferedReader(isr);
Stringline=null;
StringBuildersb=newStringBuilder();
while((line=br.readLine())!=null){
System.out.println(line);
sb.append(line);
}
is.close();
isr.close();
br.close();
returnsb.toString();
}catch(java.lang.NullPointerExceptione){
System.err.println("NullPointerException"+e.getMessage());
logger.error(cmd);
}catch(java.io.IOExceptione){
System.err.println("IOException"+e.getMessage());
}
thrownewExecuteException(cmd+"执行出错!");
}

if(SystemUtils.IS_OS_WINDOWS){
Processprocess;
try{
//process=newProcessBuilder(cmd).start();
String[]param_array=cmd.split("[\s]+");
ProcessBuilderpb=newProcessBuilder(param_array);
process=pb.start();
/*process=Runtime.getRuntime().exec(cmd);*/
intexitCode=process.waitFor();
InputStreamis=process.getInputStream();
InputStreamReaderisr=newInputStreamReader(is);
BufferedReaderbr=newBufferedReader(isr);
Stringline;
StringBuildersb=newStringBuilder();

while((line=br.readLine())!=null){
System.out.println(line);
sb.append(line);
}
is.close();
isr.close();
br.close();
returnsb.toString();
}catch(IOExceptione){
//TODOAuto-generatedcatchblock
e.printStackTrace();
}
thrownewExecuteException(cmd+"执行出错!");
}

thrownewUnHandledOSException("不支持本操作系统");
}

10. java程序执行linux命令

首先确保Linux开启sshd服务,并支持远程SSH连接。java程序使用jsch框架登录Linux,执行命令。

protected void creation() throws Exception {
JSch jsch = new JSch();
session = jsch.getSession(userName, host, port);
session.setPassword(password);
Properties config = new Properties();
config.put("StrictHostKeyChecking", "no");
session.setConfig(config);
session.setTimeout(CONNECT_TIMEOUT);
session.setConfig("PreferredAuthentications", "password,keyboard-interactive");
session.setServerAliveInterval(1000 * 60 * 2);
session.connect();
}

public String sendCommand(String command) throws Exception {
if(!isConnected())
throw new JSchException("Session is not connected, command exec faild.");
final ChannelExec exec = (ChannelExec)session.openChannel("exec");
ByteArrayOutputStream out = new ByteArrayOutputStream();
exec.setCommand(command);
exec.setOutputStream(out);
exec.setExtOutputStream(out);
exec.connect();
final Thread thread = new Thread() {
public void run() {
while(!exec.isEOF()) {
try { Thread.sleep(500L); } catch(Exception e) {}
}
}
};
thread.setDaemon(true);
thread.start();
thread.join(EXEC_TIMEOUT);
thread.interrupt();
if(thread.isAlive()) {
throw new JSchException("Exec Time Out Error");
} else {
try {
exec.disconnect();
out.close();
} catch (Exception e) {
}
byte[] lens = out.toByteArray();
String result = new String(lens, charset);
if(result.startsWith("bash") && result.indexOf("command not found") != -1)
return "";
return result;
}
}

阅读全文

与java调用linux命令相关的资料

热点内容
怎么删除一个app下载任务 浏览:713
python执行bat命令 浏览:471
什么吉他调音器app最好 浏览:33
php程序员招聘试题 浏览:14
程序员升职记第九关最优解 浏览:317
三星安卓11怎么访问data文件夹 浏览:817
华三服务器怎么设置开机自启 浏览:711
钉邮登录服务器地址 浏览:644
起源编译器适配第二款应用 浏览:433
cad弄断线条命令 浏览:463
怎么恢复手机app的安装包 浏览:300
idea重启项目不编译 浏览:495
程序员那么可爱演员表陆漓妈妈 浏览:127
linuxgadget驱动 浏览:594
华三调用acl的命令 浏览:9
资金流pdf 浏览:931
金融结算法补充条款 浏览:291
什么叫服务器怎么连接 浏览:521
空调压缩机有制冷但室内不是很冷 浏览:839
如何查解压成功 浏览:652