如何从Java代码执行命令行命令 [英] How to execute command line commands from java code
本文介绍了如何从Java代码执行命令行命令的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
大家好,
我想执行命令行命令示例
Hi All,
I want to execute a command line command example
c:/system32/ username changepassword(username,password)
其中,用户名和密码存储在变量中,例如String password ="12345"和string username ="akjilh".
请帮助我从Java代码执行此命令,任何教程或任何建议都将受到赞赏.
where username, password are stored in a variable like String password= "12345" and string username="akjilh".
please help me to execute this command from java code any tutorial or any suggestion are appreciated.
推荐答案
请参见Java ^ ]类.
See the Java Runtime[^] class.
尊敬的Sakiv,
请尝试此代码.希望这会有所帮助.
我在Linux(Fedora 16)平台上,因此我发出了命令"ls",其中列出了所有目录&文件位于当前位置,并且按预期,我将在控制台上获取输出.可以尝试发出不同的命令,因为我猜您在Windows平台上:
Dear Sakiv,
Please try this code. Hope this will help.
I''m on Linux(Fedora 16) platform hence i issued the command "ls" which lists all directories & files in current location and as expected I ''m getting the output on console. Try issuing different commands as I can guess you are on Windows Platform:
package com.srk.pkg;
import java.io.*;
public class Test {
public static void main(String[] args) {
String cmd = "ls";
Runtime run = Runtime.getRuntime();
Process pr = null;
try {
pr = run.exec(cmd);
pr.waitFor();
BufferedReader buf = new BufferedReader(new InputStreamReader(
pr.getInputStream()));
String line = "";
while ((line = buf.readLine()) != null) {
System.out.println(line);
}
} catch (Exception e) {
System.out.println(e);
}
}
}
这篇关于如何从Java代码执行命令行命令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文