转自 http://docs.oracle.com/javase/tutorial/essential/environment/cmdLineArgs.html
翻译完成,目前采用了中英对照的方式。如有翻译不周的地方,请指正。谢谢!
-----------------这里是最近有点忙的分割线,以下是中英对照,翻译不妥请指正-----------------------
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.
Java应用程序可以接受用户输入任意数量的命令行参数。这使得用户可以在程序启动时设定配置信息。
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 namedfriends.txt
, a user would enter:
在程序被调用时。用户可以在类名后面输入命令行参数。举个栗子,比如有个Java程序名为Sort, 可以在一个文档中进行行排序。如果想对一个名为friend.txt的文档进行排序的话,用户可以输入:
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 ofString
s. In the previous example, the command-line arguments passed to theSort
application in an array that contains a single String
:"friends.txt"
.
当程序启动时,运行时系统会通过一个String型数组,把命令行参数传递给程序的main方法。在之前的栗子中,命令行参数向Sort程序传递了一个只包含一个String "friends.txt"的数组。
Echoing Command-Line Arguments (Echo怎么翻译啊?感觉叫响应也不太合适嗯)
The
example displays each of its command-line arguments on a line by itself:Echo
举例:下面的Echo可以将输入的每个命令行参数在单独一行中显示
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.
下面的栗子展示了一个用户有可能运行Echo的情形.用户输入用斜体表示。
java Echo Drink Hot Java Drink Hot Java
Note that the application displays each word — Drink
, Hot
, andJava
— on a line by itself. This is because the space character separates command-line arguments. To haveDrink
,Hot
, andJava
interpreted as a single argument, the user would join them by enclosing them within quotation marks.
注意,程序将每个输入参数——Drink, Hot 和 Java——分别在各自的行里显示。这是因为空格符将三个词隔开成为三个单独的参数。如果想让Drink, Hot和Java作为一个整体参数看待,那么用户应当把他们用双引号括起来。
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 aString
argument that represents a number, such as "34", to a numeric value. Here is a code snippet that converts a command-line argument to anint
:
如果一个程序想支持数值型命令行参数,那么它必须把一个代表数字的String型参数,比如“34”,转化成数值。下面的代码片把命令行参数转换为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 ofargs[0]
isn't valid. All of theNumber
classes —Integer
,Float
, Double
, and so on — haveparseXXX
methods that convert aString
representing a number to an object of their type.
如果args[0]的格式无效,parseInt会抛出NumberFormatException的异常。所有的数值类型——int, float, double等等——必须使用相应的parseXXX方法,把String型转换成对应类型的数值。