How to launch single-file programs in Java 11 (or later)?

别来无恙 提交于 2019-12-07 11:03:47

问题


JEP 330 describes a new feature in JDK 11 for launching single-file programs in Java. I've tried:

$ ./Example.java

but it doesn't work. What is the correct usage?


回答1:


Short-version:

$ java Example.java data.txt

or (with #!):

$ ./example data.txt

Details:

Working example here.

Consider a single-file program to print the lines in a file:

import java.nio.file.*;
import java.util.stream.Stream;

public class ExampleJDK11 {
    public static void main(String[] args) throws Exception {
        // snip ... print file args[0]
    }
}

Usage 1:

Assuming the code is in Example.java and that java is on the PATH, then usage is:

java Example.java data.txt

  • Note that there is no javac step (!)
  • Note that the filename need not match the classname.

Usage 2:

Assume the code is in a file, example, with a "shebang" line at the top:

#!/Users/measter/tools/jdk-11.jdk/Contents/Home/bin/java --source 8 

import java.nio.file.*;
import java.util.stream.Stream;
// as above

Usage is:

./example data.txt




回答2:


Though the answer by you includes correct information. Just trying to put this into simpler terms, a file can simply be executed using java from JDK11 onwards, for example on MacOS

.../jdk-11.jdk/Contents/Home/bin/java Sample.java

This would seek and execute the standard public static void main(String[] args) method. As one can notice(even beginners) that this method accepts args of type String, hence the arguments placed after the name of the source file in the original command line are passed to the compiled class when it is executed. Therefore the following command

.../jdk-11.jdk/Contents/Home/bin/java <file-name>.java arg1 arg2

would provide the string arguments arg1, arg2 during the execution phase.

Side note - If the file includes multiple classes with standard main methods, the first top-level class found in the source file which shall contain the declaration of the standard public static void main(String[]) method is executed.



来源:https://stackoverflow.com/questions/51935636/how-to-launch-single-file-programs-in-java-11-or-later

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!