Search code examples
javawindowsbluej

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.


Solution

  • 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