Java 命令行编译 获得参数
2016-01-09 00:00
501 查看
Command-Line Arguments
A Java application can accept any number of arguments from the command line. This allows the user to specify configuration information when the application is launched.The user enters command-line arguments when invoking the application and specifies them after the name of the class to be run. For example, suppose a Java application called
Sortsorts lines in a file. To sort the data in a file named
friends.txt, a user would enter:
java Sort friends.txt
When an application is launched, the runtime system passes the command-line arguments to the application's main method via an array of
Strings. In the previous example, the command-line arguments passed to the
Sortapplication in an array that contains a single
String:
"friends.txt".
Echoing Command-Line Arguments
TheEchoexample displays each of its command-line arguments on a line by itself:
public class Echo { public static void main (String[] args) { for (String s: args) { System.out.println(s); } } }
The following example shows how a user might run
Echo. User input is in italics.
java Echo Drink Hot JavaDrink Hot Java
Note that the application displays each word —
Drink,
Hot, and
Java— on a line by itself. This is because the space character separates command-line arguments. To have
Drink,
Hot, and
Javainterpreted as a single argument, the user would join them by enclosing them within quotation marks.
java Echo "Drink Hot Java"Drink Hot Java
Parsing Numeric Command-Line Arguments
If an application needs to support a numeric command-line argument, it must convert aStringargument that represents a number, such as "34", to a numeric value. Here is a code snippet that converts a command-line argument to an
int:
int firstArg; if (args.length > 0) { try { firstArg = Integer.parseInt(args[0]); } catch (NumberFormatException e) { System.err.println("Argument" + args[0] + " must be an integer."); System.exit(1); } }
parseIntthrows a
NumberFormatExceptionif the format of
args[0]isn't valid. All of the
Numberclasses —
Integer,
Float,
Double, and so on — have
parseXXXmethods that convert a
Stringrepresenting a number to an object of their type.
相关文章推荐
- java对世界各个时区(TimeZone)的通用转换处理方法(转载)
- java-注解annotation
- java-模拟tomcat服务器
- java-用HttpURLConnection发送Http请求.
- java-WEB中的监听器Lisener
- Android IPC进程间通讯机制
- Android Native 绘图方法
- Android java 与 javascript互访(相互调用)的方法例子
- 介绍一款信息管理系统的开源框架---jeecg
- 聚类算法之kmeans算法java版本
- java实现 PageRank算法
- PropertyChangeListener简单理解
- c++11 + SDL2 + ffmpeg +OpenAL + java = Android播放器
- 插入排序
- 冒泡排序
- 堆排序
- 快速排序
- 二叉查找树