How to run a .class file that is part of a package from cmd?

后端 未结 12 1179
梦如初夏
梦如初夏 2020-12-01 07:11

I keep getting errors when I make my .class part of a package and try to run it from cmd.

Here\'s the code that works after using jav

相关标签:
12条回答
  • 2020-12-01 08:07

    Simple Solution in Linux, same principle:

    Say, the File is /work/packageName/file.java, with a first line:

    package packageName;
    

    Under the working directory /work/packageName/*:

    javac file.java will not work, as long as file.java contain any reference to other files in that package. The solution is to use this:

    javac --class-path  ../  file.java
    

    Or go 1 level up to /work/* and run:

    javac  ./packageName/Member.java
    

    Or simply use java instead of javac to execute.

    0 讨论(0)
  • 2020-12-01 08:09

    Run the program from the parent directory of the com directory.

    java com.HelloWorld
    
    0 讨论(0)
  • 2020-12-01 08:12

    Suppose you did cd C:/projects and HelloWorld.class is in C:/projects/com, then just type:

    java com.HelloWorld
    
    0 讨论(0)
  • 2020-12-01 08:13

    Create a folder named com under Java folder and put the HelloWorld.java into com folder. Then run again javac and java.

    0 讨论(0)
  • 2020-12-01 08:14

    Suppose the file locates at C:/projects/com/HelloWorld and you can try the following ways.

    1.java -cp c:/projects com.HelloWorld

    2.cd c:/projects
     java com.HelloWorld
    (The example 2 is not working in many situation,such as java process.)

    if there is no package declaration and there will be a little change.

    1.java -cp c:/projects/com HelloWorld

    2.cd c:/projects/com
     java HelloWorld
    (It's not good with the same reason.)

    alternatively,relative path will be ok but has some risk. Last remember put the class file in end of cmd.

    0 讨论(0)
  • 2020-12-01 08:16

    When you compile the java code, use -d, in your case, it would be

    javac -d . com.HelloWorld.java
    

    After the above command, java compiler generate a folder named "com", under the "com" folder, you will see your HelloWorld.class

    Then under the same folder as you run javac, run the following command

    java com.HelloWorld
    
    0 讨论(0)
提交回复
热议问题