import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.MongoClient;
import com.mongodb.gridfs.GridFS;
import com.mongodb.gridfs.GridFSDBFile;
import com.mongodb.gridfs.GridFSInputFile;
public class MongoDB {
public static void main(String[] args) throws IOException {
MongoClient client = new MongoClient();
DB database = client.getDB("databaseName");
FileInputStream fileInputStream = null;
GridFS videos = new GridFS(database, "videos");
try {
fileInputStream = new FileInputStream("video.mp4");
} catch (FileNotFoundException e) {
e.printStackTrace();
client.close();
System.exit(1);
}
GridFSInputFile video = videos.createFile(fileInputStream, "video.mp4");
BasicDBObject metadata = new BasicDBObject("description",
"Jennier Singing");
ArrayList<String> tags = new ArrayList<String>();
tags.add("Singing");
tags.add("Opera");
metadata.append("tags", tags);
video.setMetaData(metadata);
video.save();
System.out
.println("Object ID in Files Collection: " + video.get("_id"));
System.out.println("Saved the file to MongoDB");
System.out.println("Now let's read it back out");
GridFSDBFile gridFSDBFile = videos.findOne(new BasicDBObject(
"filename", "video.mp4"));
FileOutputStream fileOutputStream = new FileOutputStream(
"video_copy.mp4");
gridFSDBFile.writeTo(fileOutputStream);
System.out.println("Write the file back out");
fileInputStream.close();
fileOutputStream.close();
client.close();
}
}
No comments:
Post a Comment
Note: Only a member of this blog may post a comment.