本文目錄一覽:
如何在命令行運行java文件
cd
路徑,進入一個文件夾
例:cd c:\\window\user如果是一個.java類型的文件,要先編譯它才能夠運行,編譯.java文件需要安裝jdk。
javac
文件名.java,編譯一個.java文件
例:javac hello.javajava
文件名,運行一個編譯好的java文件。.java文件在編譯完成之後後生成一個.class文件,在執行java命令的時候只需要輸入文件名,不需要輸入.class這個後綴名。
例:java hello
假設編譯了一個hello.java文件,會在當前路徑下生成一個hello.class文件,執行上面的命令就可以運行了
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();
}
}
}
如何用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命令行參數。
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
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/245351.html