简体   繁体   中英

How to pass parameters to Main in java

I understand the passing of parameters to methods etc but I don't understand how I can pass extra things, such as a String (outside of the normal string array).

The problem I have is that I have a package that looks at a file and then does things to it and then decides whether there is certain text in it.

If there is then other things happen. It just so happens that these other things are contained within another package I have already coded. All that is required is that the string from Package A is passed to the main method in one of the classes in package B. I just don't know how to pass it. Is there a way of adding something like:

public static void main(String[] args,String filename) 

But then how do you call it? Just by passing main(filename) and assume that String[] args is called from the JVM automatically?

The String[] parameter of the main method contains the command line arguments you pass to the app, if you happen to run the app from cmd.exe or Bash. This is the syntax of giving the command line arguments:

java [name of the class that has the main method] [arguments]

With a .jar file instead of a .class file:

java -jar [full path of the jar] [arguments]

Each argument is separated with a space (U+0020). To create an argument that contains spaces, enclose it with double quotes. Example:

java Foo "this is one argument"

Note that the main method in any Java app must have exactly one parameter - the String[] that holds the command line arguments.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM