Vedant
Vedant

Reputation: 19

Can't run the jar file nor in Cmd

I am totally new to programming.I have just started Java and I currently work on BlueJ.My OS is windows.I don't know much about coding.So basically I just made a program.Here's it

class  Vedant {
    public static void main(String[] args) {
        int a;
        a = 1;
        if (20>a);
        a = 5;

        {
            System.out.println("Number ="+a);
        }
    }
}

I saved this as a Jar file.When I double click on the jar file it doesn't open.I have installed the latest version of Java.If I open with cmd I get an error:Unable to access jar file. I tried converting the jar file to exe using Launch4J but the exe file doesn't open.Any Help

And yea I am a Extreme Beginner in Java so I don't understand much of it.

Upvotes: 1

Views: 2728

Answers (2)

Midhun Monachan
Midhun Monachan

Reputation: 746

You will need to open the file using a terminal.

As you are a windows user, you can use command prompt.

  1. Open Command Prompt by pressing Win+R, type cmd and press Enter.
  2. Use this command for running your file in command prompt.

    java -jar (Full path to jar file)

If you get an error showing that java cannot be found, then make sure that you have java installed in your PC.

If installed, set your Java Path in your System Environment Variables.

Step by step process on how to set your Java path is given here.

After setting your java path, you will be able to run your jar file using the command.

Points to keep in mind:

  • While creating Jar file from BlueJ select main class as "Vedant" from the drop down list. By default, none(cannot be executed) is selected.

See the image

After that it can successfully be executed: (Replace C:\Users\Midhun\Desktop\vedant.jar with the link to your jar file)

C:\Users\Midhun>java -jar C:\Users\Midhun\Desktop\vedant.jar
Number =5

If you don't select the main class while creating the jar file, you will get the following error.

C:\Users\Midhun>java -jar C:\Users\Midhun\Desktop\vedant.jar
Error: Could not find or load main class 

You can overcome this error by either recreating jar with main class or executing the following command

C:\Users\Midhun>java -cp C:\Users\Midhun\Desktop\vedant.jar Vedant
Number =5

C:\Users\Midhun\Desktop\vedant.jar is the full path to jar file and Vedant is the name of main class that you want to run from the jar file.

If you give the wrong link to the jar file you will get the following error as mentioned in your question.

C:\Users\Midhun\Desktop>java -jar C:\Users\Midhun\Desktop\vedan.jar
Error: Unable to access jarfile vedan.jar

Upvotes: 2

Roni Koren Kurtberg
Roni Koren Kurtberg

Reputation: 515

You can create a .cmd file that includes the following text: java -jar path_for_your_jar_file

save it and just click on that file. It will launch your program (this is the procedure instead of entering each time to the command prompt).

Upvotes: 0

Related Questions