我尝试在Ubuntu 14.04上使用MongoDB java驱动程序。
该程序确实可以通过编译阶段,但在运行时,它只是有这个错误:
Exception in thread "main" java.lang.NoClassDefFoundError: com/mongodb/MongoClient
at App.main(App.java:23)
Caused by: java.lang.ClassNotFoundException: com.mongodb.MongoClient
at java.net.URLClassLoader$1.run(URLClassLoader.java:366)
at java.net.URLClassLoader$1.run(URLClassLoader.java:355)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:354)
at java.lang.ClassLoader.loadClass(ClassLoader.java:425)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:308)
at java.lang.ClassLoader.loadClass(ClassLoader.java:358)
... 1 more
我的Java版本是1.7,我确实尝试过1.6,但是发生了同样的错误。 我的编译命令是:
javac App.java -classpath mongo-java-driver-2.13.0.jar
我使用命令运行程序:
java App
以下是我的Java代码:
import com.mongodb.BasicDBObject;
import com.mongodb.BulkWriteOperation;
import com.mongodb.BulkWriteResult;
import com.mongodb.Cursor;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.DBObject;
import com.mongodb.MongoClient;
import com.mongodb.ParallelScanOptions;
import com.mongodb.MongoException;
import com.mongodb.ServerAddress;
import java.util.List;
import java.util.Set;
public class App
{
public static void main(String[] args)
{
System.out.println("----- Program Start -----");
try {
MongoClient mongoClient = new MongoClient("localhost" , 27017);
DB db = mongoClient.getDB("demo");
System.out.println("Connect to database successfully.");
DBCollection coll = db.getCollection("test");
BasicDBObject doc = new BasicDBObject();
for(int i = 0; i < 10; i++) {
doc.append("A" + Integer.toString(i), 12.56);
}
System.out.println(doc);
} catch (Exception e) {
System.err.println(e.getClass().getName() + ": ");
e.getMessage();
}
}
}
有人可以帮忙吗?谢谢!
答案 0 :(得分:2)
编译和执行都需要类路径。以下调用应该起作用
java App -classpath mongo-java-driver-2.13.0.jar