简体   繁体   中英

Modifying a main method to take a text file when compiling the java file

How can I make a main method take a text file as an argument on the command line?

So for example

java ClassWithMainMethod textFileNeededInMainMethod.txt

I've been told this is possible but I'm not sure how it's done.

You use the String[] args from the Java program entry point like

public static void main(String[] args) {
  if (args.length < 1) {
    System.err.println("no file provided");
    System.exit(1);
  }
  File f = new File(args[0]);
  // ...
}

That if could be used to set a default file if one isn't provided. Finally, it's a good idea to use File.canRead() before you try and read from a file.

The arguments passed to main are of type string so you'd pass the name of the file or path of the file and then create a file object and then read its content.

You can't pass the type file to a java main class

In your main method, the args array contains any arguments. For example, if you typed java ClassWithMainMethod textFileNeededInMainMethod.txt , then you could read the argument like this:

public static void main(String[] args) {
    String file = "";
    if(args.length > 0) file = args[0];
}

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