Running Java Program from Command Line Linux

前端 未结 4 1977
無奈伤痛
無奈伤痛 2020-12-08 08:24

I am not very experience with java and this is driving me crazy. I wrote a java program FileManagement and I need to run it from the command line.

I can

相关标签:
4条回答
  • 2020-12-08 08:38

    Guys let's understand the syntax of it.

    1. If class file is present in the Current Dir.

      java -cp . fileName

    2. If class file is present within the Dir. Go to the Parent Dir and enter below cmd.

      java -cp . dir1.dir2.dir3.fileName

    3. If there is a dependency on external jars then,

      java -cp .:./jarName1:./jarName2 fileName

      Hope this helps.

    0 讨论(0)
  • 2020-12-08 08:41

    (This is the KISS answer.)

    Let's say you have several .java files in the current directory:

    $ ls -1 *.java
    javaFileName1.java
    javaFileName2.java
    

    Let's say each of them have a main() method (so they are programs, not libs), then to compile them do:

    javac *.java -d .
    

    This will generate as many subfolders as "packages" the .java files are associated to. In my case all java files where inside under the same package name packageName, so only one folder was generated with that name, so to execute each of them:

    java -cp . packageName.javaFileName1
    java -cp . packageName.javaFileName2
    
    0 讨论(0)
  • 2020-12-08 08:42

    What is the package name of your class? If there is no package name, then most likely the solution is:

    java -cp FileManagement Main
    
    0 讨论(0)
  • 2020-12-08 08:53

    If your Main class is in a package called FileManagement, then try:

    java -cp . FileManagement.Main
    

    in the parent folder of the FileManagement folder.

    If your Main class is not in a package (the default package) then cd to the FileManagement folder and try:

    java -cp . Main
    

    More info about the CLASSPATH and how the JRE find classes:

    • How Classes are Found
    • Setting the class path (Solaris/Linux)
    • http://en.wikipedia.org/wiki/Classpath_(Java)
    0 讨论(0)
提交回复
热议问题