7

I am testing out maven and its capabilities. I am trying to write a string to a text file using commons-io

import org.apache.commons.io.FileUtils;
...
public void writeToFile(String fileName){
    File file = new File(fileName);
    ...
    FileUtils.writeStringToFile(file,rowEntry); //rowEntry is a String
}  

I have added the commons-io to the dependencies

POM.xml

<dependency>
    <groupId>commons-io</groupId>
    <artifactId>commons-io</artifactId>
    <version>2.5</version>
 </dependency>  

It compiles but it throws an exception when I run it

Exception in thread "main" java.lang.NoClassDefFoundError: org/apache/commons/io/FileUtils
at com.RandCollections.StringFinder.writeToFile(StringFinder.java:704)
at com.RandCollections.StringFinder.menu(StringFinder.java:123)
at com.RandCollections.StringFinderMain.main(StringFinderMain.java:28)
Caused by: java.lang.ClassNotFoundException: org.apache.commons.io.FileUtils
at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:331)
at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
... 3 more   

I think Im missing out on some things, can you help point it out please?

Dee
  • 401
  • 3
  • 9
  • 22

2 Answers2

7

If it compiles fine but throws the exception when running, it means the dependency was on classpath when compiling but not when running the code.

Maven is responsible for compile classpath, and did provide the dependency on compile time. You'll have to check how you run the application and make sure the maven dependencies are also on the runtime classpath - that has nothing to do with Maven, unless you run the code as a part of unit tests.

Jiri Tousek
  • 12,211
  • 5
  • 29
  • 43
  • 2
    thanks for the idea, i was missing a plugin to be added in the pom.xml, works fine now. – Dee Jun 23 '16 at 01:25
  • 4
    which plugin, I have the same problem. – Ali Taha Sep 12 '18 at 12:07
  • @AliTaha I had the same problem and got it working using the [exec-maven-plugin](https://www.mojohaus.org/exec-maven-plugin/). Then can just run `mvn exec:java`. I'm not sure why just normally compiling and running didn't work though, other dependencies were working fine for me. – RyanQuey May 12 '20 at 14:00
0

you can try adding library to your classpath ex:

javac -classpath fileUtillibraywhatever.jar YourClass.java

EDIT:

If your main class is in a package

package com.yourpackage.test;
public class YourClass
{}

then

   javac -classpath fileUtillibraywhatever.jar com/yourpackage/test/YourClass.java 

and run

java -classpath fileUtillibraywhatever.jar com/yourpackage/test/YourClass

I hope it helps.. If you are working with iDE https://wiki.eclipse.org/FAQ_How_do_I_add_an_extra_library_to_my_project's_classpath%3F

ZaoTaoBao
  • 2,567
  • 2
  • 20
  • 28