Netbeans how to set command line arguments in Java
Solution 1:
I am guessing that you are running the file using Run | Run File
(or shift-F6) rather than Run | Run Main Project
. The NetBeans 7.1 help file (F1 is your friend!) states for the Arguments parameter:
Add arguments to pass to the main class during application execution. Note that arguments cannot be passed to individual files.
I verified this with a little snippet of code:
public class Junk
{
public static void main(String[] args)
{
for (String s : args)
System.out.println("arg -> " + s);
}
}
I set Run -> Arguments to x y z
. When I ran the file by itself I got no output. When I ran the project the output was:
arg -> x
arg -> y
arg -> z
Solution 2:
-
Create the Java code that can receive an argument as a command line argument.
class TestCode{ public static void main(String args[]){ System.out.println("first argument is: "+args[0]); } }
Run the program without arguments (press F6).
In the Output window, at the bottom, click the double yellow arrow (or the yellow button) to open a Run dialog.
If the argument you need to pass is
testArgument
, then here in this window pass the argument asapplication.args=testArgument
.
This will give the output as follows in the same Output window:
first argument is: testArgument
For Maven, the instructions are similar, but change the exec.args
property instead:
exec.args=-classpath %classpath package.ClassName PARAM1 PARAM2 PARAM3
Note: Use single quotes for string parameters that contain spaces.