Search code examples
javajar

I get an error: An unexpected error occurred while trying to open file hola.jar


i am using Linux ubuntu and i have created a java program named hola.java which is the following program code, this program works perfectly

import javax.swing.*;
import java.awt.*;

public class hola extends JFrame {

JButton b1 = new JButton("presionar");

 hola(){

  super("Botones");
  setSize(250,250);
  setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  FlowLayout flo=new FlowLayout();
  setLayout(flo);
  add(b1);
  setVisible(true);

  }

  public static void main(String[] args)
 {


    hola bt = new hola();
   }

}

This java program works perfectly when it runs Now I created a jar file of this program using in command line:

jar cf hola.jar hola.class

This creates a Jar file named hola.jar

I even wrote Main-Class: hola in the manifest.mf file.

When I try to run this by:

java -jar hola.jar

I get an error: An unexpected error occurred while trying to open file hola.jar

Please tell me how to run jar file so that I get an output :'( , what could be the possible reason that i can not run this program as a jar file, even the program works perfectly using "java hola.java"


Solution

  • To run a java file within a jar file, you don't need to open it. You simply need to ensure your classpath is having the given jar file

    If the class is within a package then you can run using

    java -cp hola.jar package.hola
    

    If the class is not in a package then simply use

    java -cp hola.jar hola
    

    If you are not within the directory where hola.jar is located, then you can try following:

    • In case of within package

      java -cp /locationOfJar/hola.jar package.hola

    • or In case of not in package

      java -cp /locationOfJar/hola.jar hola