I am having trouble understanding how to actually use the command line to run a big java project ( by big I mean with multiple files and folder).
Imagine I have a project containing :
~/src/main/fr/file1.java ~/src/main/fr/file2.java ~/src/test/test1.java
All my life people have done the makefile for me. I just code the java src with vim and compile and run with make
. Now there is no makefile ! I compile with maven (that I am still understanding how it works.). After compiling with maven (I just run maven compile). I then have a new folder named target.
~/target/main/fr/file1.class ~/target/main/fr/file2.class ~/target/test/test1.class
Now how can I run test1
? I tried using java -classpath =... test1
but I always get errors …
If can someone help me (or just give me some resources so I can finally understand basic project structuring and scripting) it will be amazing. Thank you !
Advertisement
Answer
Here is a minimal working example to compile java source files from multiple locations and pack them in a single runnable jar.
$ tree . ├── makefile ├── src_folder_1 │ └── Main.java └── src_folder_2 └── Person.java
The contents of java files appear at the end for completeness. Here is the makefile.
BIN_DIR = bin WITH_DEBUG_INFO = -g .DEFAULT_GOAL: app.jar: compile_phase.done: ${SRC_FILES} @mkdir -p ${BIN_DIR} @javac ${WITH_DEBUG_INFO} ${SRC_FILES} -d ${BIN_DIR} @echo "DONE" >> $@ manifest.mf: @echo "Class-Path: ${BIN_DIR}/*.classnMain-Class: Mainn" > $@ app.jar: manifest.mf compile_phase.done @jar cfm $@ $< -C ${BIN_DIR} . @rm -rf ${BIN_DIR} @rm $^
See that all java source files are compiled within the same rule, and the corresponding *.class
files are put in a dedicated bin
directory. To emphasize that everything needed to run the jar is inside it I completely removed the bin
directory and the manifest.mf
. Now you can run the program with
$ java -jar app.jar oren Hello oren
Here are the java files for completeness:
$ cat src_folder_1/Main.java class Main { static public void main(String[] args) { Person p = new Person(args[0]); System.out.format("Hello %sn",p.toString()); }} $ cat src_folder_2/Person.java class Person { private String name; public Person(String n) { this.name = n;} public String toString() { return name; }}