0

I am writing a java program for a project. I am using Maven as a manager. I have tried two approaches:

1.

mvn clean install

mvn dependency:copy-dependencies

java -cp target/Main-1.0-SNAPSHOT.jar:dependency com.company.main.Main

The first two commands work fine, and I can see the dependencies in target/dependencies class. But when I run the program, I get the error

Exception in thread "main" java.lang.NoClassDefFoundError: org/apache/commons/validator/routines/checkdigit/LuhnCheckDigit

So it can't find my dependency.

2.

My second approach is to use mvn exec:java. This has worked, but the project spec says I need to provide an input file through either the command line, or STDIN. I can use -Dexec.systemin=input.txt, but I dont know how to use mvn exec:java with STDIN. I tried < input.txt but this does not work. Should I go with trying the first method, or can I use STDIN with exec:java?

paul88
  • 51
  • 6
  • 1
    What you want is a "fat jar". [Building a fat jar using maven](https://stackoverflow.com/q/16222748/2970947). – Elliott Frisch Nov 11 '21 at 04:38
  • 1
    Does this answer your question? [Building a fat jar using maven](https://stackoverflow.com/questions/16222748/building-a-fat-jar-using-maven) – seenukarthi Nov 11 '21 at 04:41
  • I dont think this is necessary, I am just trying to compile and run a simple program in a terminal, a fat jar seems like overkill. – paul88 Nov 11 '21 at 04:45
  • @ElliottFrisch I will look into this, but do you know why the first option is not working? The mvn dependency:copy-dependencies is working but it can't find them when running. – paul88 Nov 11 '21 at 04:56
  • `target/Main-1.0-SNAPSHOT.jar:dependency` isn't all of your dependencies. I know that's a credit card validator it's failing on. You didn't include your pom. So it's hard to give you a definitive answer. – Elliott Frisch Nov 11 '21 at 05:13
  • @ElliottFrisch The dependency is in my pom, and when I would run using intelliJ it worked. Anyways I found a solution. I looked at your comment and added the maven-shade-plugin to my pom. Then, I ran mvn package and two jar files were in my target Main-SNAPSHOT and original-Main-SNAPSHOT. Now, java -cp target/Main-1.0-SNAPSHOT.jar:dependency com.company.main.Main input.txt and java -cp target/Main-1.0-SNAPSHOT.jar:dependency com.company.main.Main < input.txt both work. Is this because a fat jar was made? I want to understand why this works. – paul88 Nov 11 '21 at 05:29
  • Yes. A fat (or uber) jar packages all of the dependencies into a single jar file. Note, with the proper `pom` contents (which you still haven't shown us) you can use `java -jar target/Main-1.0-SNAPSHOT.jar input.txt` (btw `< input.txt` is stdin while `input.txt` alone is `args[0]` to `main`). – Elliott Frisch Nov 11 '21 at 05:59
  • @ElliottFrisch The project is a for a job interview so I am trying to not give away much information. Anyways, you have helped a lot, thank you! – paul88 Nov 11 '21 at 15:04

0 Answers0