Java 连接Mongodb 数据库并且从数据库导出数据为Json文件。
需要导入三个包:
bson-3.4.3.jar mongo-java-driver-3.4.3.jar
mongodb-driver-core-3.4.3.jar
当然版本可以改变。可以从http://mongodb.github.io/mongo-java-driver/ 这里下载
mongodb.properties:
url=localhost
port=27017
将数据导出为Json文件
public static void main(String[] args) throws IOException {
String url = null;
int port=27017;
//加载
Properties p = new Properties();
InputStream input = MongoDbConn.class.getClassLoader().getResourceAsStream("mongodb.properties");
try {
p.load(input);
url = p.getProperty("url");
port = Integer.valueOf(p.getProperty("port"));
} catch (IOException e) {
e.printStackTrace();
}finally{
if (input != null) {
try {
input.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
MongoClient mongoClient = new MongoClient(url, port);
MongoDatabase md =mongoClient.getDatabase("local");
System.out.println(md.getName());
MongoCollection<Document> mo=md.getCollection("student");
FindIterable<Document> f=mo.find();
MongoCursor<Document> cm=f.iterator();
String Json = "";
while(cm.hasNext()){
Json = Json + cm.next().toJson();
}
System.out.println(Json);
//将Json文件 存入文件
String Path = "F:/" + "1.txt";
File file = new File(Path);
if(file.exists()){
System.out.println("文件存在");
}
else{
file.createNewFile();
FileOutputStream fileOutputStream = new FileOutputStream(file);
fileOutputStream.write(Json.getBytes());
fileOutputStream.close();
System.out.println("文件创建成功");
}
}