java 编译参数_Java 命令行编译 获得参数

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 calledSort sorts 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 Sort application in an array that contains a single String: "friends.txt".

Echoing Command-Line Arguments

The Echo example 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 haveDrink, Hot, and Java interpreted 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 a String argument 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);

}

}

parseInt throws a NumberFormatException if the format of args[0] isn't valid. All of the Number classes — Integer, Float, Double, and so on — have parseXXXmethods that convert a String representing a number to an object of their type.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值