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?
$ java Example.java data.txt
or (with #!
):
$ ./example data.txt
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]
}
}
Assuming the code is in Example.java
and that java
is on the PATH
, then usage is:
java Example.java data.txt
javac
step (!)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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With