Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
151 views
in Technique[技术] by (71.8m points)

java - How to compile and run with this folder structure

I have my java source files in src/net/... folders and .jar files in lib folder. How to compile and run this files with command line without writing build script ?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Lets say you have your code files in

[someDirectory]
  |
  +-[lib]
  |  |
  |  +-someLib.jar
  |  +-someOtherLib.jar
  |  +-...
  |
  +--[src]
       |
       +-[net]
           |
           +-[name]
                |
                +-[one]
                   |
                   +-[two]
                       |
                       +-[main]
                           |
                           +-Main.java <- code you want to compile
                                          and execute

then if your console is in

someDirectory>

you can compile it with

someDirectory>javac -cp "lib*" src
et
ameonewomainMain.java

but this will produce Main.class file in same directory as Main.java so to execute code from net.name.one.two.main.Main class you would need to include src directory to classPath because this directory contains package that Main class is placed, so you would need to use command

someDirectory>java -cp "src;lib*" net.name.one.two.main.Main

But it is good practice to separate class files from source files. To do this you can add -d (directory) parameter while compiling pass directory which should have compiled class files. So first create your classes directory at the same level as src directory and execute

someDirectory>javac -d "classes" -cp "lib*" src
et
ameonewomainMain.java

and now to be able to execute your Main class instead creating confusion by src directory to classPath you will have to add classes directory which is more intuitive.

someDirectory>java -cp "classes;lib*" net.name.one.two.main.Main.java

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...