简体   繁体   中英

How to run compiled java project from console, not from IntelliJ

After the the demo project is compiled, there are many .class file in the out>production>testPrj>apidemo. Basically, each file will have one .class file

I expect to enter the console:

java apidemo.class

but it doesn't work.

I tried "java apidemo.class". The error msg is "Error: Could not find or load main class apidemo".

I also read this post . It is not working for my situation. My compile is success, and it can be run from Intellj, but I don't know how to run it from console. How do I run a compiled java project from console?

在此处输入图片说明

For running from console you have to do few things:

  • to be sure that your class apidemo.ApiDemo has main() for lunching your program.
  • compile sources - navigate to folder where is source file located (it has already compiled by Intellij):

    javac ApiDemo.java

  • run compiled files with .class extension, providing full class name (with packages):

    java apidemo.ApiDemo

You need to provide the fully qualified name of the class with package name and not include ".class". So you need to place yourself in the parent directory to where ApiDemo.class is - ie out>production>testPrj.

And then execute:

$ java apidemo.ApiDemo

Another way is to provide "out/production/testPrj" as the classpath:

$ java -cp /path/to/out/production/testPrj apidemo.ApiDemo

If the class is in a package:

package mypackagename;

public class MyClassName {
  public static final void main(String[] cmdLineParams)  {
  } 
}

You need to use:

java -classpath . MyClassName

Notice the "."
It must be called with its fully-qualified name:

java -classpath . mypackagename.MyClassName

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