本文目录一览:
java命令行参数。
import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.BasicParser;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.CommandLine;
public static void main(String[] args) throws Exception {
// Create a Parser
CommandLineParser parser = new BasicParser( );
Options options = new Options( );
options.addOption("h", "help", false, "Print this usage information");
options.addOption("v", "verbose", false, "Print out VERBOSE information" );
options.addOption("f", "file", true, "File to save program output to");
// Parse the program arguments
CommandLine commandLine = parser.parse( options, args );
// Set the appropriate variables based on supplied options
boolean verbose = false;
String file = "";
if( commandLine.hasOption('h') ) {
System.out.println( "Help Message")
System.exit(0);
}
if( commandLine.hasOption('v') ) {
verbose = true;
}
if( commandLine.hasOption('f') ) {
file = commandLine.getOptionValue('f');
}
}
cli下载地址:
上面是代码片段使用方法:
java xxxx -h
java xxxx -f 119
如何用java执行命令行
Java运行命令行并获取返回值,下面以简单的Java执行ping命令(ping 127.0.0.1 -t
)为例,代码如下:
Process p = Runtime.getRuntime().exec("ping 127.0.0.1 -t");
Process p = Runtime.getRuntime().exec("javac");
InputStream is = p.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
String line;
while((line = reader.readLine())!= null){
System.out.println(line);
}
p.waitFor();
is.close();
reader.close();
p.destroy();
}
java中如何执行命令行语句
可以使用java.lang.Process和java.lang.Runtime实现,下面展示两个例子,其它用法请查阅资料:
1、执行ping命令:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class ProcessTest {
public static void main(String[] args) {
BufferedReader br = null;
try {
String cmd = "ping 127.0.0.1";
// 执行dos命令并获取输出结果
Process proc = Runtime.getRuntime().exec(cmd);
br = new BufferedReader(new InputStreamReader(proc.getInputStream(), "GBK"));
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
proc.waitFor();
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
2、打开浏览器并跳转到百度首页:
import java.io.IOException;
public class ProcessTest {
public static void main(String[] args) {
try {
String exeFullPathName = "C:/Program Files/Internet Explorer/IEXPLORE.EXE";
String message = "";
String[] cmd = {exeFullPathName, message};
Process proc = Runtime.getRuntime().exec(cmd);
} catch (IOException e) {
e.printStackTrace();
}
}
}