简体   繁体   中英

Java executable command line

I need to create an executable as a result of a Makefile. Something as simple as if the user types abc, followed by the required input, in the command line the program executes. The code was written in Java. My Makefile runs just fine but I am not sure of how to create that executable. The name of the main method is Main.java just in case is necessary

The full execution would be something like:

abc xxxx

Where xxxx is the user's input. I am getting NullPointers when reading the input. I have tried using Scanner , BufferedReader , and System.console().system() and keep getting the same error.

Any advice on reading the input?

Thanks

You can use the jar command to convert a Java class to an executable:

jar -cmf manifest.txt YourProgram.class

Provided you have a mainfest.txt manifest file with at least this row:

Main-Class: YourProgram

If you want to run your code from the command line then you have to navigate to the location of your java file. The commands for that depend on which operating system you are using. After navigating to the correct folder you can create byte code using the javac >name< command where name is your program name. A separate file with the same name as your program should be created. You can run that using the java >name< command and add the arguments after the program name.

like: java name 1

Here another answer: How do I run a Java program from the command line on Windows?

The right command once you compiled your program with javac is this:

jar cfn output.jar manifest.txt program.class

EDIT: The n option is deprecated, your can use m instead with no other change.

Where output is the name of your executable, manifest should contain at least one line:

Main-Class: program

and after that you can add as many classes as you need to.

Once you are done with that, the next step is to use some utility to convert the .jar to .exe . I recommend Launch4J since it is very easy to use and multi platform.

Let's assume your command

abc xxxx

looks like one of these:

java Main xxxx
java -cp ... Main xxxx
java -jar ... xxxx

then you can access the second part xxxx like so:

public class Main {
    public static void main(String[] args) {
        System.out.println("main called with " + args);
    }
}

You cannot access the command line parameters on stdin or anywhere else, that is why your other attempts failed.

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