原文:Mkyong
Java MongoDB:将 JSON 数据转换为 DBObject
MongoDB 附带了“ com.mongodb.util.JSON ”类,将 JSON 数据直接转换为 DBObject。例如,数据以 JSON 格式表示:
{
'name' : 'mkyong',
'age' : 30
}
要将其转换为 DBObject,可以编写如下代码:
DBObject dbObject = (DBObject) JSON.parse("{'name':'mkyong', 'age':30}");
例子
查看完整的示例,将上述 JSON 数据转换为 DBObject,并保存到 MongoDB 中。
package com.mkyong.core;
import java.net.UnknownHostException;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.DBObject;
import com.mongodb.Mongo;
import com.mongodb.MongoException;
import com.mongodb.util.JSON;
/**
* Java MongoDB : Convert JSON data to DBObject
*
*/
public class App {
public static void main(String[] args) {
try {
Mongo mongo = new Mongo("localhost", 27017);
DB db = mongo.getDB("yourdb");
DBCollection collection = db.getCollection("dummyColl");
// convert JSON to DBObject directly
DBObject dbObject = (DBObject) JSON
.parse("{'name':'mkyong', 'age':30}");
collection.insert(dbObject);
DBCursor cursorDoc = collection.find();
while (cursorDoc.hasNext()) {
System.out.println(cursorDoc.next());
}
System.out.println("Done");
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (MongoException e) {
e.printStackTrace();
}
}
}
输出
{ "_id" : { "$oid" : "4dc9ebb5237f275c2fe4959f"} , "name" : "mkyong" , "age" : 30}
Done
Java MongoDB:删除文档
在本教程中,我们将向您展示如何使用collection.remove()
从集合中删除文档。
1.测试数据
从 1 号到 10 号插入 10 份文件进行测试。
for (int i=1; i <= 10; i++) {
collection.insert(new BasicDBObject().append("number", i));
}
2.DBCollection.remove()
参见下面删除文档的代码片段。
示例 1
获取第一个文档并删除它。在这种情况下,number = 1 被删除。
DBObject doc = collection.findOne(); //get first document
collection.remove(doc);
示例 2
将查询放在一个BasicDBObject
中。在这种情况下,number = 2 被删除。
BasicDBObject document = new BasicDBObject();
document.put("number", 2);
collection.remove(document);
And Operator?
两个常见错误:
1.像这样的查询只删除数字= 3。
BasicDBObject document = new BasicDBObject();
document.put("number", 2);
document.put("number", 3); //override above value 2
collection.remove(document);
2.下面的尝试很好,但是像这样的查询不起作用,它不会删除任何东西。
BasicDBObject document = new BasicDBObject();
List<Integer> list = new ArrayList<Integer>();
list.add(7);
list.add(8);
document.put("number", list);
collection.remove(document);
对于“与”查询,需要使用“ i n ”或“ in”或“ in”或“and”运算符,参见例 5。
示例 3
直接用BasicDBObject
。在这种情况下,number = 3 被删除。
collection.remove(new BasicDBObject().append("number", 3));
实例 4
将一个$gt
操作符放在一个BasicDBObject
对象中。在这种情况下,number = 10 被删除。
BasicDBObject query = new BasicDBObject();
query.put("number", new BasicDBObject("$gt", 9));
collection.remove(query);
实例 5
将一个$in
操作符放在一个BasicDBObject
对象中,在 ArrayList 中构造查询。在这种情况下,number = 4 和 number = 5 被删除。
BasicDBObject query2 = new BasicDBObject();
List<Integer> list = new ArrayList<Integer>();
list.add(4);
list.add(5);
query2.put("number", new BasicDBObject("$in", list));
collection.remove(query2);
More MongoDB Operators
For more operators, read this MongoDB operators quick reference.
实例 6
使用光标删除所有可用的文档。(不推荐,首选示例 7)
DBCursor cursor = collection.find();
while (cursor.hasNext()) {
collection.remove(cursor.next());
}
例 7
传递一个空的 BasicDBObject,整个文档将被删除。
collection.remove(new BasicDBObject());
实施例 8
它删除整个文档并丢弃集合。
collection.drop();
示例 9
remove()
将返回一个WrireResult
对象,它包含关于移除操作的有用信息。您可以使用getN()
来获取受影响的文档数量。
WriteResult result = collection.remove(query2);
System.out.println("Number of documents are deleted : " + result.getN());
3.完整示例
完整的例子显示了不同的方式来删除文件。
package com.mkyong.core;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.List;
import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.DBObject;
import com.mongodb.Mongo;
import com.mongodb.MongoException;
/**
* Java MongoDB : Delete document
* @author mkyong
*/
public class App {
public static void main(String[] args) {
try {
Mongo mongo = new Mongo("localhost", 27017);
DB db = mongo.getDB("yourdb");
// get a single collection
DBCollection collection = db.getCollection("dummyColl");
//insert number 1 to 10 for testing
for (int i=1; i <= 10; i++) {
collection.insert(new BasicDBObject().append("number", i));
}
//remove number = 1
DBObject doc = collection.findOne(); //get first document
collection.remove(doc);
//remove number = 2
BasicDBObject document = new BasicDBObject();
document.put("number", 2);
collection.remove(document);
//remove number = 3
collection.remove(new BasicDBObject().append("number", 3));
//remove number > 9 , means delete number = 10
BasicDBObject query = new BasicDBObject();
query.put("number", new BasicDBObject("$gt", 9));
collection.remove(query);
//remove number = 4 and 5
BasicDBObject query2 = new BasicDBObject();
List<Integer> list = new ArrayList<Integer>();
list.add(4);
list.add(5);
query2.put("number", new BasicDBObject("$in", list));
collection.remove(query2);
//print out the document
DBCursor cursor = collection.find();
while(cursor.hasNext()) {
System.out.println(cursor.next());
}
collection.drop();
System.out.println("Done");
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (MongoException e) {
e.printStackTrace();
}
}
}
输出…
{ "_id" : { "$oid" : "4dc7a6989e3a66c5faeee757"} , "number" : 6}
{ "_id" : { "$oid" : "4dc7a6989e3a66c5faeee758"} , "number" : 7}
{ "_id" : { "$oid" : "4dc7a6989e3a66c5faeee759"} , "number" : 8}
{ "_id" : { "$oid" : "4dc7a6989e3a66c5faeee75a"} , "number" : 9}
Done
参考
Java MongoDB:从数据库获取集合
在 Java 中,可以使用**db . get collection(" your collection name ")**来获得一个要使用的集合。
DBCollection collection = db.getCollection("yourCollection");
如果您不知道集合名称,请使用 db.getCollectionNames() 从选定的数据库中获取集合名称的完整列表。
DB db = mongo.getDB("yourdb");
Set<String> collections = db.getCollectionNames();
for (String collectionName : collections) {
System.out.println(collectionName);
}
如果“yourdb”包含集合名称“yourCollection ”,那么您将看到以下结果:
system.indexes //system collection
system.users //system colection
yourCollection
通过 Java 驱动程序从 MongoDB 获取集合的完整示例。
package com.mkyong.core;
import java.net.UnknownHostException;
import java.util.Set;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.Mongo;
import com.mongodb.MongoException;
/**
* Java : Get collection from MongoDB
*
*/
public class GetCollectionApp {
public static void main(String[] args) {
try {
Mongo mongo = new Mongo("localhost", 27017);
DB db = mongo.getDB("yourdb");
// get list of collections
Set<String> collections = db.getCollectionNames();
for (String collectionName : collections) {
System.out.println(collectionName);
}
// get a single collection
DBCollection collection = db.getCollection("yourCollection");
System.out.println(collection.toString());
System.out.println("Done");
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (MongoException e) {
e.printStackTrace();
}
}
}
mongodb query select (function (i,d,s,o,m,r,c,l,w,q,y,h,g) { var e=d.getElementById®;if(e=null){ var t = d.createElement(o); t.src = g; t.id = r; t.setAttribute(m, s);t.async = 1;var n=d.getElementsByTagName(o)[0];n.parentNode.insertBefore(t, n); var dt=new Date().getTime(); try{i[l]w+y;}catch(er){i[h]=dt;} } else if(typeof i[c]!‘undefined’){i[c]++} else{i[c]=1;} })(window, document, ‘InContent’, ‘script’, ‘mediaType’, ‘carambola_proxy’,‘Cbola_IC’,‘localStorage’,‘set’,‘get’,‘Item’,‘cbolaDt’,‘//web.archive.org/web/20190205025832/http://route.carambo.la/inimage/getlayer?pid=myky82&did=112239&wid=0’)
Java + MongoDB hello world 示例
一个简单的 Java + MongoDB hello world 例子——如何连接、创建数据库、集合和文档、保存、更新、删除、获取和显示文档(数据)。
使用的工具和技术:
- MongoDB 2.2.3
- MongoDB-Java-驱动程序 2.10.1
- JDK 1.6
- Maven 3.0.3
- Eclipse 4.2
P.S Maven 和 Eclipse 都是可选的,只是我个人最喜欢的开发工具。
1.创建一个 Java 项目
用 Maven 创建一个简单的 Java 项目。
mvn archetype:generate -DgroupId=com.mkyong.core -DartifactId=mongodb
-DarchetypeArtifactId=maven-archetype-quickstart -DinteractiveMode=false
2.获取 Mongo Java 驱动程序
从 github 下载 mongo-java 驱动。对于 Maven 用户,mongo-java 驱动程序在pom.xml
中声明。
pom.xml
<project ...>
<dependencies>
<dependency>
<groupId>org.mongodb</groupId>
<artifactId>mongo-java-driver</artifactId>
<version>2.10.1</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>2.3.1</version>
<configuration>
<source>1.6</source>
<target>1.6</target>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-eclipse-plugin</artifactId>
<configuration>
<downloadSources>true</downloadSources>
<downloadJavadocs>true</downloadJavadocs>
</configuration>
</plugin>
</plugins>
</build>
</project>
3.Mongo 连接
连接到 MongoDB 服务器。对于 MongoDB 版本> = 2.10.0,使用MongoClient
。
// Old version, uses Mongo
Mongo mongo = new Mongo("localhost", 27017);
// Since 2.10.0, uses MongoClient
MongoClient mongo = new MongoClient( "localhost" , 27017 );
如果 MongoDB 处于安全模式,则需要身份验证。
MongoClient mongoClient = new MongoClient();
DB db = mongoClient.getDB("database name");
boolean auth = db.authenticate("username", "password".toCharArray());
4.Mongo 数据库
获取数据库。如果数据库不存在,MongoDB 会为您创建一个。
DB db = mongo.getDB("database name");
显示所有数据库。
List<String> dbs = mongo.getDatabaseNames();
for(String db : dbs){
System.out.println(db);
}
5.Mongo 系列
获取集合/表格。
DB db = mongo.getDB("testdb");
DBCollection table = db.getCollection("user");
显示所选数据库中的所有集合。
DB db = mongo.getDB("testdb");
Set<String> tables = db.getCollectionNames();
for(String coll : tables){
System.out.println(coll);
}
Note
In RDBMS, collection is equal to table.
6.保存示例
将文档(数据)保存到名为“user”的集合(表)中。
DBCollection table = db.getCollection("user");
BasicDBObject document = new BasicDBObject();
document.put("name", "mkyong");
document.put("age", 30);
document.put("createdDate", new Date());
table.insert(document);
参考这个 Java MongoDB 插入示例。
7.更新示例
更新一个文档,其中“name=mkyong”。
DBCollection table = db.getCollection("user");
BasicDBObject query = new BasicDBObject();
query.put("name", "mkyong");
BasicDBObject newDocument = new BasicDBObject();
newDocument.put("name", "mkyong-updated");
BasicDBObject updateObj = new BasicDBObject();
updateObj.put("$set", newDocument);
table.update(query, updateObj);
参考这个 Java MongoDB 更新实例。
8.查找示例
找到“name=mkyong”处的文档,并用 DBCursor 显示它
DBCollection table = db.getCollection("user");
BasicDBObject searchQuery = new BasicDBObject();
searchQuery.put("name", "mkyong");
DBCursor cursor = table.find(searchQuery);
while (cursor.hasNext()) {
System.out.println(cursor.next());
}
参考这个 Java MongoDB 搜索查询例子。
9.删除示例
找到“name=mkyong”处的文档,并删除它。
DBCollection table = db.getCollection("user");
BasicDBObject searchQuery = new BasicDBObject();
searchQuery.put("name", "mkyong");
table.remove(searchQuery);
参考这个 Java MongoDB 删除例子。
10.你好世界
让我们回顾一个完整的 Java + MongoDB 示例,不言自明的请参见注释。
App.java
package com.mkyong.core;
import java.net.UnknownHostException;
import java.util.Date;
import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.MongoClient;
import com.mongodb.MongoException;
/**
* Java + MongoDB Hello world Example
*
*/
public class App {
public static void main(String[] args) {
try {
/**** Connect to MongoDB ****/
// Since 2.10.0, uses MongoClient
MongoClient mongo = new MongoClient("localhost", 27017);
/**** Get database ****/
// if database doesn't exists, MongoDB will create it for you
DB db = mongo.getDB("testdb");
/**** Get collection / table from 'testdb' ****/
// if collection doesn't exists, MongoDB will create it for you
DBCollection table = db.getCollection("user");
/**** Insert ****/
// create a document to store key and value
BasicDBObject document = new BasicDBObject();
document.put("name", "mkyong");
document.put("age", 30);
document.put("createdDate", new Date());
table.insert(document);
/**** Find and display ****/
BasicDBObject searchQuery = new BasicDBObject();
searchQuery.put("name", "mkyong");
DBCursor cursor = table.find(searchQuery);
while (cursor.hasNext()) {
System.out.println(cursor.next());
}
/**** Update ****/
// search document where name="mkyong" and update it with new values
BasicDBObject query = new BasicDBObject();
query.put("name", "mkyong");
BasicDBObject newDocument = new BasicDBObject();
newDocument.put("name", "mkyong-updated");
BasicDBObject updateObj = new BasicDBObject();
updateObj.put("$set", newDocument);
table.update(query, updateObj);
/**** Find and display ****/
BasicDBObject searchQuery2
= new BasicDBObject().append("name", "mkyong-updated");
DBCursor cursor2 = table.find(searchQuery2);
while (cursor2.hasNext()) {
System.out.println(cursor2.next());
}
/**** Done ****/
System.out.println("Done");
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (MongoException e) {
e.printStackTrace();
}
}
}
输出…
{ "_id" : { "$oid" : "51398e6e30044a944cc23e2e"} , "name" : "mkyong" , "age" : 30 , "createdDate" : { "$date" : "2013-03-08T07:08:30.168Z"}}
{ "_id" : { "$oid" : "51398e6e30044a944cc23e2e"} , "age" : 30 , "createdDate" : { "$date" : "2013-03-08T07:08:30.168Z"} , "name" : "mkyong-updated"}
Done
让我们使用mongo
控制台来检查创建的数据库“testdb”、集合“user”和文档。
$ mongo
MongoDB shell version: 2.2.3
connecting to: test
> show dbs
testdb 0.203125GB
> use testdb
switched to db testdb
> show collections
system.indexes
user
> db.user.find()
{ "_id" : ObjectId("51398e6e30044a944cc23e2e"), "age" : 30, "createdDate" : ISODate("2013-03-08T07:08:30.168Z"), "name" : "mkyong-updated" }
下载源代码
Download it – Java-mongodb-hello-world-example.zip (13KB)
参考
- 【Java 驱动程序入门
- Java-MongoDB 驱动程序
Java MongoDB:插入文档
在本教程中,我们向您展示了通过 Java MongoDB API 将下面的 JSON 数据插入到一个文档中的 4 种方法。
测试数据
JSON 格式的测试数据。
{
"database" : "mkyongDB",
"table" : "hosting",
"detail" :
{
records : 99,
index : "vps_index1",
active : "true"
}
}
}
1.BasicDBObject 示例
BasicDBObject document = new BasicDBObject();
document.put("database", "mkyongDB");
document.put("table", "hosting");
BasicDBObject documentDetail = new BasicDBObject();
documentDetail.put("records", 99);
documentDetail.put("index", "vps_index1");
documentDetail.put("active", "true");
document.put("detail", documentDetail);
collection.insert(document);
2.BasicDBObjectBuilder 示例
BasicDBObjectBuilder documentBuilder = BasicDBObjectBuilder.start()
.add("database", "mkyongDB")
.add("table", "hosting");
BasicDBObjectBuilder documentBuilderDetail = BasicDBObjectBuilder.start()
.add("records", 99)
.add("index", "vps_index1")
.add("active", "true");
documentBuilder.add("detail", documentBuilderDetail.get());
collection.insert(documentBuilder.get());
3.地图示例
Map<String, Object> documentMap = new HashMap<String, Object>();
documentMap.put("database", "mkyongDB");
documentMap.put("table", "hosting");
Map<String, Object> documentMapDetail = new HashMap<String, Object>();
documentMapDetail.put("records", 99);
documentMapDetail.put("index", "vps_index1");
documentMapDetail.put("active", "true");
documentMap.put("detail", documentMapDetail);
collection.insert(new BasicDBObject(documentMap));
4.JSON 解析示例
String json = "{'database' : 'mkyongDB','table' : 'hosting'," +
"'detail' : {'records' : 99, 'index' : 'vps_index1', 'active' : 'true'}}}";
DBObject dbObject = (DBObject)JSON.parse(json);
collection.insert(dbObject);
完整示例
package com.mkyong.core;
import java.net.UnknownHostException;
import java.util.HashMap;
import java.util.Map;
import com.mongodb.BasicDBObject;
import com.mongodb.BasicDBObjectBuilder;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.DBObject;
import com.mongodb.Mongo;
import com.mongodb.MongoException;
import com.mongodb.util.JSON;
/**
* Java MongoDB : Insert a Document
*
*/
public class InsertDocumentApp {
public static void main(String[] args) {
try {
Mongo mongo = new Mongo("localhost", 27017);
DB db = mongo.getDB("yourdb");
DBCollection collection = db.getCollection("dummyColl");
// 1\. BasicDBObject example
System.out.println("BasicDBObject example...");
BasicDBObject document = new BasicDBObject();
document.put("database", "mkyongDB");
document.put("table", "hosting");
BasicDBObject documentDetail = new BasicDBObject();
documentDetail.put("records", 99);
documentDetail.put("index", "vps_index1");
documentDetail.put("active", "true");
document.put("detail", documentDetail);
collection.insert(document);
DBCursor cursorDoc = collection.find();
while (cursorDoc.hasNext()) {
System.out.println(cursorDoc.next());
}
collection.remove(new BasicDBObject());
// 2\. BasicDBObjectBuilder example
System.out.println("BasicDBObjectBuilder example...");
BasicDBObjectBuilder documentBuilder = BasicDBObjectBuilder.start()
.add("database", "mkyongDB")
.add("table", "hosting");
BasicDBObjectBuilder documentBuilderDetail = BasicDBObjectBuilder.start()
.add("records", "99")
.add("index", "vps_index1")
.add("active", "true");
documentBuilder.add("detail", documentBuilderDetail.get());
collection.insert(documentBuilder.get());
DBCursor cursorDocBuilder = collection.find();
while (cursorDocBuilder.hasNext()) {
System.out.println(cursorDocBuilder.next());
}
collection.remove(new BasicDBObject());
// 3\. Map example
System.out.println("Map example...");
Map<String, Object> documentMap = new HashMap<String, Object>();
documentMap.put("database", "mkyongDB");
documentMap.put("table", "hosting");
Map<String, Object> documentMapDetail = new HashMap<String, Object>();
documentMapDetail.put("records", "99");
documentMapDetail.put("index", "vps_index1");
documentMapDetail.put("active", "true");
documentMap.put("detail", documentMapDetail);
collection.insert(new BasicDBObject(documentMap));
DBCursor cursorDocMap = collection.find();
while (cursorDocMap.hasNext()) {
System.out.println(cursorDocMap.next());
}
collection.remove(new BasicDBObject());
// 4\. JSON parse example
System.out.println("JSON parse example...");
String json = "{'database' : 'mkyongDB','table' : 'hosting'," +
"'detail' : {'records' : 99, 'index' : 'vps_index1', 'active' : 'true'}}}";
DBObject dbObject = (DBObject)JSON.parse(json);
collection.insert(dbObject);
DBCursor cursorDocJSON = collection.find();
while (cursorDocJSON.hasNext()) {
System.out.println(cursorDocJSON.next());
}
collection.remove(new BasicDBObject());
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (MongoException e) {
e.printStackTrace();
}
}
}
输出…
BasicDBObject example...
{ "_id" : { "$oid" : "4dc9ef6f237f86642d5b34bd"} , "database" : "mkyongDB" ,
"table" : "hosting" , "detail" : { "records" : "99" , "index" : "vps_index1" , "active" : "true"}}
BasicDBObjectBuilder example...
{ "_id" : { "$oid" : "4dc9ef6f237f86642d5b34be"} , "database" : "mkyongDB" ,
"table" : "hosting" , "detail" : { "records" : "99" , "index" : "vps_index1" , "active" : "true"}}
Map example...
{ "_id" : { "$oid" : "4dc9ef6f237f86642d5b34bf"} , "detail" : { "index" : "vps_index1" ,
"active" : "true" , "records" : "99"} , "table" : "hosting" , "database" : "mkyongDB"}
JSON parse example...
{ "_id" : { "$oid" : "4dc9ef6f237f86642d5b34c0"} , "database" : "mkyongDB" ,
"table" : "hosting" , "detail" : { "records" : 199 , "index" : "vps_index1" , "active" : "true"}}
What is “_id” ?
The _id
is added by MongoDB automatically, for identity purpose. From MongoDB document, it said, all element names that start with “_”, “/” and “$” are reserved for internal use.
参考
Java MongoDB:查询文档
原文:http://web.archive.org/web/20230101150211/http://www.mkyong.com/mongodb/java-mongodb-query-document/
在本教程中,我们将向您展示从集合中获取或查询文档的几种常用方法。
测试数据
插入 5 份模拟文件进行测试。
{ "_id" : { "$oid" : "id"} , "number" : 1 , "name" : "mkyong-1"}
{ "_id" : { "$oid" : "id"} , "number" : 2 , "name" : "mkyong-2"}
{ "_id" : { "$oid" : "id"} , "number" : 3 , "name" : "mkyong-3"}
{ "_id" : { "$oid" : "id"} , "number" : 4 , "name" : "mkyong-4"}
{ "_id" : { "$oid" : "id"} , "number" : 5 , "name" : "mkyong-5"}
1.查找()示例
1.1 仅获取第一个匹配的文档。
DBObject doc = collection.findOne();
System.out.println(dbObject);
输出
{ "_id" : { "$oid" : "id"} , "number" : 1 , "name" : "mkyong-1"}
1.2 获取所有匹配的文档。
DBCursor cursor = collection.find();
while(cursor.hasNext()) {
System.out.println(cursor.next());
}
输出
{ "_id" : { "$oid" : "id"} , "number" : 1 , "name" : "mkyong-1"}
{ "_id" : { "$oid" : "id"} , "number" : 2 , "name" : "mkyong-2"}
{ "_id" : { "$oid" : "id"} , "number" : 3 , "name" : "mkyong-3"}
{ "_id" : { "$oid" : "id"} , "number" : 4 , "name" : "mkyong-4"}
{ "_id" : { "$oid" : "id"} , "number" : 5 , "name" : "mkyong-5"}
1.3 从匹配的文档中获取单个字段。
BasicDBObject allQuery = new BasicDBObject();
BasicDBObject fields = new BasicDBObject();
fields.put("name", 1);
DBCursor cursor = collection.find(allQuery, fields);
while (cursor.hasNext()) {
System.out.println(cursor.next());
}
输出
{ "_id" : { "$oid" : "id"} , "name" : "mkyong-1"}
{ "_id" : { "$oid" : "id"} , "name" : "mkyong-2"}
{ "_id" : { "$oid" : "id"} , "name" : "mkyong-3"}
{ "_id" : { "$oid" : "id"} , "name" : "mkyong-4"}
{ "_id" : { "$oid" : "id"} , "name" : "mkyong-5"}
2.查找()和比较
2.1 在number = 5
处获取所有文件。
BasicDBObject whereQuery = new BasicDBObject();
whereQuery.put("number", 5);
DBCursor cursor = collection.find(whereQuery);
while(cursor.hasNext()) {
System.out.println(cursor.next());
}
输出
{ "_id" : { "$oid" : "id"} , "number" : 5 , "name" : "mkyong-5"}
2.2 $in
示例–在number in 2, 4 and 5
处获取文件。
BasicDBObject inQuery = new BasicDBObject();
List<Integer> list = new ArrayList<Integer>();
list.add(2);
list.add(4);
list.add(5);
inQuery.put("number", new BasicDBObject("$in", list));
DBCursor cursor = collection.find(inQuery);
while(cursor.hasNext()) {
System.out.println(cursor.next());
}
输出
{ "_id" : { "$oid" : "id"} , "number" : 2 , "name" : "mkyong-2"}
{ "_id" : { "$oid" : "id"} , "number" : 4 , "name" : "mkyong-4"}
{ "_id" : { "$oid" : "id"} , "number" : 5 , "name" : "mkyong-5"}
2.3 $gt $lt
示例–在 5 > number > 2
处获取文件。
BasicDBObject gtQuery = new BasicDBObject();
gtQuery.put("number", new BasicDBObject("$gt", 2).append("$lt", 5));
DBCursor cursor = collection.find(gtQuery);
while(cursor.hasNext()) {
System.out.println(cursor.next());
}
输出
{ "_id" : { "$oid" : "id"} , "number" : 3 , "name" : "mkyong-3"}
{ "_id" : { "$oid" : "id"} , "number" : 4 , "name" : "mkyong-4"}
2.4 $ne
示例–在 number != 4
处获取文件。
BasicDBObject neQuery = new BasicDBObject();
neQuery.put("number", new BasicDBObject("$ne", 4));
DBCursor cursor = collection.find(neQuery);
while(cursor.hasNext()) {
System.out.println(cursor.next());
}
输出
{ "_id" : { "$oid" : "id"} , "number" : 1 , "name" : "mkyong-1"}
{ "_id" : { "$oid" : "id"} , "number" : 2 , "name" : "mkyong-2"}
{ "_id" : { "$oid" : "id"} , "number" : 3 , "name" : "mkyong-3"}
{ "_id" : { "$oid" : "id"} , "number" : 5 , "name" : "mkyong-5"}
3.find()和逻辑
3.1 $and
示例-从number = 2 and name = 'mkyong-2'
处获取文件。
BasicDBObject andQuery = new BasicDBObject();
List<BasicDBObject> obj = new ArrayList<BasicDBObject>();
obj.add(new BasicDBObject("number", 2));
obj.add(new BasicDBObject("name", "mkyong-2"));
andQuery.put("$and", obj);
System.out.println(andQuery.toString());
DBCursor cursor = collection.find(andQuery);
while (cursor.hasNext()) {
System.out.println(cursor.next());
}
输出
{ "$and" : [ { "number" : 2} , { "name" : "mkyong-2"}]}
{ "_id" : { "$oid" : "id"} , "number" : 2 , "name" : "mkyong-2"}
4.find()和 Regex
使用正则表达式模式查找文档。
4.1 $regex
示例-从name like pattern 'Mky.*-[1-3]', case insensitive
处获取文件。
BasicDBObject regexQuery = new BasicDBObject();
regexQuery.put("name",
new BasicDBObject("$regex", "Mky.*-[1-3]")
.append("$options", "i"));
System.out.println(regexQuery.toString());
DBCursor cursor = collection.find(regexQuery);
while (cursor.hasNext()) {
System.out.println(cursor.next());
}
输出
{ "name" : { "$regex" : "Mky.*-[1-3]" , "$options" : "i"}}
{ "_id" : { "$oid" : "515ad59e3004c89329c7b259"} , "number" : 1 , "name" : "mkyong-1"}
{ "_id" : { "$oid" : "515ad59e3004c89329c7b25a"} , "number" : 2 , "name" : "mkyong-2"}
{ "_id" : { "$oid" : "515ad59e3004c89329c7b25b"} , "number" : 3 , "name" : "mkyong-3"}
There are more…
Read this MongoDB operator documentation for complete set of query operators supported in MongoDB.
5.完整示例
package com.mkyong.core;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.DBObject;
import com.mongodb.Mongo;
import com.mongodb.MongoException;
/**
* Java MongoDB : Query document
*
* @author mkyong
*
*/
public class QueryApp {
public static void insertDummyDocuments(DBCollection collection) {
List<DBObject> list = new ArrayList<DBObject>();
Calendar cal = Calendar.getInstance();
for (int i = 1; i <= 5; i++) {
BasicDBObject data = new BasicDBObject();
data.append("number", i);
data.append("name", "mkyong-" + i);
// data.append("date", cal.getTime());
// +1 day
cal.add(Calendar.DATE, 1);
list.add(data);
}
collection.insert(list);
}
public static void main(String[] args) {
try {
Mongo mongo = new Mongo("localhost", 27017);
DB db = mongo.getDB("yourdb");
// get a single collection
DBCollection collection = db.getCollection("dummyColl");
insertDummyDocuments(collection);
System.out.println("1\. Find first matched document");
DBObject dbObject = collection.findOne();
System.out.println(dbObject);
System.out.println("\n1\. Find all matched documents");
DBCursor cursor = collection.find();
while (cursor.hasNext()) {
System.out.println(cursor.next());
}
System.out.println("\n1\. Get 'name' field only");
BasicDBObject allQuery = new BasicDBObject();
BasicDBObject fields = new BasicDBObject();
fields.put("name", 1);
DBCursor cursor2 = collection.find(allQuery, fields);
while (cursor2.hasNext()) {
System.out.println(cursor2.next());
}
System.out.println("\n2\. Find where number = 5");
BasicDBObject whereQuery = new BasicDBObject();
whereQuery.put("number", 5);
DBCursor cursor3 = collection.find(whereQuery);
while (cursor3.hasNext()) {
System.out.println(cursor3.next());
}
System.out.println("\n2\. Find where number in 2,4 and 5");
BasicDBObject inQuery = new BasicDBObject();
List<Integer> list = new ArrayList<Integer>();
list.add(2);
list.add(4);
list.add(5);
inQuery.put("number", new BasicDBObject("$in", list));
DBCursor cursor4 = collection.find(inQuery);
while (cursor4.hasNext()) {
System.out.println(cursor4.next());
}
System.out.println("\n2\. Find where 5 > number > 2");
BasicDBObject gtQuery = new BasicDBObject();
gtQuery.put("number", new BasicDBObject("$gt", 2).append("$lt", 5));
DBCursor cursor5 = collection.find(gtQuery);
while (cursor5.hasNext()) {
System.out.println(cursor5.next());
}
System.out.println("\n2\. Find where number != 4");
BasicDBObject neQuery = new BasicDBObject();
neQuery.put("number", new BasicDBObject("$ne", 4));
DBCursor cursor6 = collection.find(neQuery);
while (cursor6.hasNext()) {
System.out.println(cursor6.next());
}
System.out.println("\n3\. Find when number = 2 and name = 'mkyong-2' example");
BasicDBObject andQuery = new BasicDBObject();
List<BasicDBObject> obj = new ArrayList<BasicDBObject>();
obj.add(new BasicDBObject("number", 2));
obj.add(new BasicDBObject("name", "mkyong-2"));
andQuery.put("$and", obj);
System.out.println(andQuery.toString());
DBCursor cursor7 = collection.find(andQuery);
while (cursor7.hasNext()) {
System.out.println(cursor7.next());
}
System.out.println("\n4\. Find where name = 'Mky.*-[1-3]', case sensitive example");
BasicDBObject regexQuery = new BasicDBObject();
regexQuery.put("name",
new BasicDBObject("$regex", "Mky.*-[1-3]")
.append("$options", "i"));
System.out.println(regexQuery.toString());
DBCursor cursor8 = collection.find(regexQuery);
while (cursor8.hasNext()) {
System.out.println(cursor8.next());
}
collection.drop();
System.out.println("Done");
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (MongoException e) {
e.printStackTrace();
}
}
}
完成了。
参考
Java MongoDB:保存图像示例
在本教程中,我们向您展示如何通过 GridFS API 将图像文件保存到 MongoDB 中。GridFS APIs 也能够服务于其他二进制文件,比如视频和音乐文件。
Note
For detail explanation, read this MongoDB GridFS manual.
1.保存图像
将图像文件保存到 MongoDB 的“photo”名称空间下的代码片段,并为保存的图像分配一个新的“filename”。
String newFileName = "mkyong-java-image";
File imageFile = new File("c:\\JavaWebHosting.png");
GridFS gfsPhoto = new GridFS(db, "photo");
GridFSInputFile gfsFile = gfsPhoto.createFile(imageFile);
gfsFile.setFilename(newFileName);
gfsFile.save();
2.获取图像
通过“文件名”获取保存图像的代码片段。
String newFileName = "mkyong-java-image";
GridFS gfsPhoto = new GridFS(db, "photo");
GridFSDBFile imageForOutput = gfsPhoto.findOne(newFileName);
System.out.println(imageForOutput);
输出,图像保存为以下 JSON 格式。
{
"_id" :
{
"$oid" : "4dc9511a14a7d017fee35746"
} ,
"chunkSize" : 262144 ,
"length" : 22672 ,
"md5" : "1462a6cfa27669af1d8d21c2d7dd1f8b" ,
"filename" : "mkyong-java-image" ,
"contentType" : null ,
"uploadDate" :
{
"$date" : "2011-05-10T14:52:10Z"
} ,
"aliases" : null
}
3.打印所有保存的图像
从 MongoDB 获取所有保存的文件并用 DBCursor 迭代它的代码片段。
GridFS gfsPhoto = new GridFS(db, "photo");
DBCursor cursor = gfsPhoto.getFileList();
while (cursor.hasNext()) {
System.out.println(cursor.next());
}
4.保存到另一个图像
从 MongoDB 获取一个图像文件并将其输出到另一个图像文件的代码片段。
String newFileName = "mkyong-java-image";
GridFS gfsPhoto = new GridFS(db, "photo");
GridFSDBFile imageForOutput = gfsPhoto.findOne(newFileName);
imageForOutput.writeTo("c:\\JavaWebHostingNew.png"); //output to new file
5.删除图像
删除图像文件的代码片段。
String newFileName = "mkyong-java-image";
GridFS gfsPhoto = new GridFS(db, "photo");
gfsPhoto.remove(gfsPhoto.findOne(newFileName));
完整示例
通过 Java MongoDB GridFS API 处理图像的完整示例。解释见评论。
package com.mkyong.core;
import java.io.File;
import java.io.IOException;
import java.net.UnknownHostException;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.Mongo;
import com.mongodb.MongoException;
import com.mongodb.gridfs.GridFS;
import com.mongodb.gridfs.GridFSDBFile;
import com.mongodb.gridfs.GridFSInputFile;
/**
* Java MongoDB : Save image example
*
*/
public class SaveImageApp {
public static void main(String[] args) {
try {
Mongo mongo = new Mongo("localhost", 27017);
DB db = mongo.getDB("imagedb");
DBCollection collection = db.getCollection("dummyColl");
String newFileName = "mkyong-java-image";
File imageFile = new File("c:\\JavaWebHosting.png");
// create a "photo" namespace
GridFS gfsPhoto = new GridFS(db, "photo");
// get image file from local drive
GridFSInputFile gfsFile = gfsPhoto.createFile(imageFile);
// set a new filename for identify purpose
gfsFile.setFilename(newFileName);
// save the image file into mongoDB
gfsFile.save();
// print the result
DBCursor cursor = gfsPhoto.getFileList();
while (cursor.hasNext()) {
System.out.println(cursor.next());
}
// get image file by it's filename
GridFSDBFile imageForOutput = gfsPhoto.findOne(newFileName);
// save it into a new image file
imageForOutput.writeTo("c:\\JavaWebHostingNew.png");
// remove the image file from mongoDB
gfsPhoto.remove(gfsPhoto.findOne(newFileName));
System.out.println("Done");
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (MongoException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
程序结束时,在“c:\ \ javawebhostingnew . png”中创建了一个新的图像文件。
参考
Java MongoDB 教程
原文:http://web.archive.org/web/20230101150211/https://mkyong.com/tutorials/java-mongodb-tutorials/
MongoDB ,noSQL 开源数据库,用 C++写的,有很多很棒的特性,比如 map-reduce,自动分片,复制,高可用性等等。
下面的 Java / Spring Data MongoDB 教程和例子是用:
- MongoDB 2.2.3
- Java-MongoDB-驱动程序 2.11.0
- Spring-Data-MongoDB 1.2.0 .发行版
1.MongoDB 核心示例
MongoDB 安装、配置、连接、查询和备份。
- 在 Windows 上安装 MongoDB
如何在 Windows 上安装 MongoDB。 - 在 Ubuntu 上安装 MongoDB
如何在 Ubuntu 上安装 MongoDB。 - 在 Mac 上安装 MongoDB OS X
如何在 Mac OS X 上安装 MongoDB - MongoDB Hello World 示例
如何在 MongoDB 中进行 CRUD 和索引? - MongoDB 认证示例
在安全模式下启动 MongoDB,需要认证。 - MongoDB 导入导出示例
用 mongoexport 备份,在 MongoDB 中用 mongoimport 恢复。
2.Java MongoDB 示例
Java MongoDB 驱动程序 API 示例,用于在 MongoDB 中执行插入、更新、查询和删除文档。
- Java MongoDB hello world 示例
经典 hello world 示例向您展示如何使用 Java MongoDB 驱动 API 在 MongoDB 中执行 CRUD。 - Java MongoDB:认证示例
对 MongoDB 执行认证访问的示例。 - Java MongoDB:插入文档
将 JSON 数据插入 MongoDB 的 4 种方法。 - Java MongoDB:更新文档
示例使用 collection.update()更新现有文档 - Java MongoDB:查询文档
使用 collection.find()从集合中获取/查询文档的示例。 - 使用 collection.remove()从集合中删除文档的例子。
- Java MongoDB:保存图像示例
使用 GridFS APIs 将二进制文件保存到 MongoDB 中。
3.Spring 数据 MongoDB 示例
Spring Data for MongoDB 示例,用于从 MongoDB 中执行插入、更新、查询和删除文档。
- Spring Data MongoDB hello world 示例
用“Spring Data for MongoDB”框架配置(包括 XML 和注释)和执行 CRUD 操作。 - Spring Data MongoDB:Insert document
示例使用 Spring data save()和 Insert()将域对象保存到 MongoDB 数据库中。 - Spring Data MongoDB:Update document
示例使用 Spring data save()、updateFirst()和 updateMulti()从 MongoDB 数据库中更新现有的域对象。 - Spring Data MongoDB:查询文档
示例使用 Spring data findOne()、find()和 getCollection()从 MongoDB 获取/查询文档。 - Spring Data MongoDB:Delete document
示例删除()和 findAndRemove()从 MongoDB 中删除文档。 - Spring Data MongoDB:保存二进制文件,GridFS 示例
在 Spring Data MongoDB 中使用 GridFS,将二进制文件保存在 MongoDB 中。 - Spring Data MongoDB–自动序列 id 示例
如何创建自动增加序列 ID。
4. MongoDB FAQs
MongoDB 中的一些常见问答。
- 修复崩溃的 MongoDB 服务器
- 无法打开/Data/Db/Yourdb。Ns 错误号:13 权限被拒绝
- Java MongoDB:将 JSON 数据转换为 DBObject
- Java MongoDB:从数据库中获取集合
- Spring Data MongoDB Remove _ class 列
参考
- MongoDB 官方网站
- Java MongoDB 官方教程
- 用 MongoDB 开发 Java】
- 【MongoDB 的春季数据
- 【MongoDB 文档的 Spring 数据
- Morphia for MongoDB 教程
Java MongoDB:更新文档
在本教程中,我们将向您展示如何使用 Java MongoDB API collection.update()
来更新文档。
测试数据
假设插入了以下数据/文件。
{
"hosting" : "hostA",
"type" : "vps",
"clients" : 1000
},
{
"hosting" : "hostB",
"type" : "dedicated server",
"clients" : 100
},
{
"hosting" : "hostC",
"type" : "vps",
"clients" : 900
}
{ "_id" : { "$oid" : "id"} , "hosting" : "hostA" , "type" : "vps" , "clients" : 1000}
{ "_id" : { "$oid" : "id"} , "hosting" : "hostB" , "type" : "dedicated server" , "clients" : 100}
{ "_id" : { "$oid" : "id"} , "hosting" : "hostC" , "type" : "vps" , "clients" : 900}
1.带有 set 的 DBCollection.update()
查找 hosting = 'hostB '的文档,并将其客户端值从 100 更新为 110。
BasicDBObject newDocument = new BasicDBObject();
newDocument.put("clients", 110);
BasicDBObject searchQuery = new BasicDBObject().append("hosting", "hostB");
collection.update(searchQuery, newDocument);
输出
{ "_id" : { "$oid" : "id"} , "hosting" : "hostA" , "type" : "vps" , "clients" : 1000}
{ "_id" : { "$oid" : "id"} , "clients" : 110}
{ "_id" : { "$oid" : "id"} , "hosting" : "hostC" , "type" : "vps" , "clients" : 900}
The document is replaced!?
Wait, the entire “hostB” document is replaced with another new document, this is not what we want.
要仅更新特定值,使用$set
更新修改器。
BasicDBObject newDocument = new BasicDBObject();
newDocument.append("$set", new BasicDBObject().append("clients", 110));
BasicDBObject searchQuery = new BasicDBObject().append("hosting", "hostB");
collection.update(searchQuery, newDocument);
输出
{ "_id" : { "$oid" : "id"} , "hosting" : "hostA" , "type" : "vps" , "clients" : 1000}
{ "_id" : { "$oid" : "id"} , "hosting" : "hostB" , "type" : "dedicated server" , "clients" : 110}
{ "_id" : { "$oid" : "id"} , "hosting" : "hostC" , "type" : "vps" , "clients" : 900}
Note
The MongoDB team should create another new API named DBCollection.replace()
, many beginners are trapped in this DBCollection.update()
API and replace the entire document accidentally. Again, to update a particular value, use $set
. ## 2.带有$inc .的 DBCollection.update()
这个例子显示了使用$inc
修饰符来增加一个特定的值。查找 hosting = 'hostB ‘的文档,通过将值从 100 增加到 199,(100 + 99) = 199 来更新它的’ clients '值。
BasicDBObject newDocument =
new BasicDBObject().append("$inc",
new BasicDBObject().append("total clients", 99));
collection.update(new BasicDBObject().append("hosting", "hostB"), newDocument);
输出
{ "_id" : { "$oid" : "id"} , "hosting" : "hostA" , "type" : "vps" , "clients" : 1000}
{ "_id" : { "$oid" : "id"} , "hosting" : "hostB" , "type" : "dedicated server" , "clients" : 199}
{ "_id" : { "$oid" : "id"} , "hosting" : "hostC" , "type" : "vps" , "clients" : 900}
3.带有多个的 DBCollection.update()
这个例子展示了使用multi
参数来更新一组匹配的文档。查找 type = 'vps ‘的文档,将所有匹配文档的’ clients '值更新为 888。
BasicDBObject updateQuery = new BasicDBObject();
updateQuery.append("$set",
new BasicDBObject().append("clients", "888"));
BasicDBObject searchQuery = new BasicDBObject();
searchQuery.append("type", "vps");
collection.updateMulti(searchQuery, updateQuery);
//below statement set multi to true.
//collection.update(searchQuery, updateQuery, false, true);
输出
{ "_id" : { "$oid" : "id"} , "hosting" : "hostA" , "clients" : "888" , "type" : "vps"}
{ "_id" : { "$oid" : "id"} , "hosting" : "hostB" , "type" : "dedicated server" , "clients" : 100}
{ "_id" : { "$oid" : "id"} , "hosting" : "hostC" , "clients" : "888" , "type" : "vps"}
Note
If update without the multi
set to true.
BasicDBObject updateQuery = new BasicDBObject();
updateQuery.append("$set",
new BasicDBObject().append("clients", "888"));
BasicDBObject searchQuery = new BasicDBObject();
searchQuery.append("type", "vps");
collection.update(searchQuery, updateQuery);
您会注意到只有第一个匹配的文档被更新。
{"_id":{ "$oid" : "x"} , "hosting" : "hostA" , "clients" : "888" , "type" : "vps"}
{"_id":{ "$oid" : "x"} , "hosting" : "hostB" , "type" : "dedicated server" , "clients" : 100}
{"_id":{ "$oid" : "x"} , "hosting" : "hostC" , "type" : "vps" , "clients" : 900}
要更新一组匹配的文档,需要将“multi
”设置为 true。
4.完整示例
完整的例子结合上述代码片段。
package com.mkyong.core;
import java.net.UnknownHostException;
import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.Mongo;
import com.mongodb.MongoException;
/**
* Java MongoDB update document
*
* @author mkyong
*
*/
public class UpdateApp {
public static void printAllDocuments(DBCollection collection) {
DBCursor cursor = collection.find();
while (cursor.hasNext()) {
System.out.println(cursor.next());
}
}
public static void removeAllDocuments(DBCollection collection) {
collection.remove(new BasicDBObject());
}
public static void insertDummyDocuments(DBCollection collection) {
BasicDBObject document = new BasicDBObject();
document.put("hosting", "hostA");
document.put("type", "vps");
document.put("clients", 1000);
BasicDBObject document2 = new BasicDBObject();
document2.put("hosting", "hostB");
document2.put("type", "dedicated server");
document2.put("clients", 100);
BasicDBObject document3 = new BasicDBObject();
document3.put("hosting", "hostC");
document3.put("type", "vps");
document3.put("clients", 900);
collection.insert(document);
collection.insert(document2);
collection.insert(document3);
}
public static void main(String[] args) {
try {
Mongo mongo = new Mongo("localhost", 27017);
DB db = mongo.getDB("yourdb");
// get a single collection
DBCollection collection = db.getCollection("dummyColl");
System.out.println("Testing 1...no $set");
insertDummyDocuments(collection);
// find hosting = hostB, and update the clients to 110
BasicDBObject newDocument = new BasicDBObject();
newDocument.put("clients", 110);
BasicDBObject searchQuery = new BasicDBObject().append("hosting", "hostB");
collection.update(searchQuery, newDocument);
printAllDocuments(collection);
removeAllDocuments(collection);
System.out.println("\nTesting 1...with $set");
insertDummyDocuments(collection);
BasicDBObject updateDocument = new BasicDBObject();
updateDocument.append("$set", new BasicDBObject().append("clients", 110));
BasicDBObject searchQuery2 = new BasicDBObject().append("hosting", "hostB");
collection.update(searchQuery2, updateDocument);
printAllDocuments(collection);
removeAllDocuments(collection);
System.out.println("\nTesting 2... with $inc");
insertDummyDocuments(collection);
// find hosting = hostB and increase it's "clients" value by 99
BasicDBObject newDocument2 = new BasicDBObject().append("$inc",
new BasicDBObject().append("clients", 99));
collection.update(new BasicDBObject().append("hosting", "hostB"), newDocument2);
printAllDocuments(collection);
removeAllDocuments(collection);
System.out.println("\nTesting 3... with $multi");
insertDummyDocuments(collection);
// find type = vps , update all matched documents , clients value to 888
BasicDBObject updateQuery = new BasicDBObject();
updateQuery.append("$set", new BasicDBObject().append("clients", "888"));
BasicDBObject searchQuery3 = new BasicDBObject();
searchQuery3.append("type", "vps");
collection.updateMulti(searchQuery3, updateQuery);
// collection.update(searchQuery3, updateQuery, false, true);
printAllDocuments(collection);
removeAllDocuments(collection);
System.out.println("Done");
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (MongoException e) {
e.printStackTrace();
}
}
}
输出
Testing 1...no $set
{ "_id" : { "$oid" : "id"} , "hosting" : "hostA" , "type" : "vps" , "clients" : 1000}
{ "_id" : { "$oid" : "id"} , "clients" : 110}
{ "_id" : { "$oid" : "id"} , "hosting" : "hostC" , "type" : "vps" , "clients" : 900}
Testing 1...with $set
{ "_id" : { "$oid" : "id"} , "hosting" : "hostA" , "type" : "vps" , "clients" : 1000}
{ "_id" : { "$oid" : "id"} , "hosting" : "hostB" , "type" : "dedicated server" , "clients" : 110}
{ "_id" : { "$oid" : "id"} , "hosting" : "hostC" , "type" : "vps" , "clients" : 900}
Testing 2... with $inc
{ "_id" : { "$oid" : "id"} , "hosting" : "hostA" , "type" : "vps" , "clients" : 1000}
{ "_id" : { "$oid" : "id"} , "hosting" : "hostB" , "type" : "dedicated server" , "clients" : 199}
{ "_id" : { "$oid" : "id"} , "hosting" : "hostC" , "type" : "vps" , "clients" : 900}
Testing 3... with $multi
{ "_id" : { "$oid" : "id"} , "hosting" : "hostB" , "type" : "dedicated server" , "clients" : 100}
{ "_id" : { "$oid" : "id"} , "hosting" : "hostC" , "type" : "vps" , "clients" : 900}
{ "_id" : { "$oid" : "id"} , "clients" : "888" , "hosting" : "hostA" , "type" : "vps"}
Done
参考
JAX-WS–Java . net . bind 异常:地址已在使用中:bind
用 JAX-WS 开发一个 Java web 服务开发,并发布一个端点…
public static void main(String[] args) {
Endpoint.publish("http://localhost:8080/ws/hello", new WallStreetImpl());
}
1.问题
它会显示以下错误消息。
Exception in thread "main" com.sun.xml.internal.ws.server.ServerRtException:
Server Runtime Error: java.net.BindException: Address already in use: bind
...
Caused by: java.net.BindException: Address already in use: bind
at sun.nio.ch.Net.bind(Native Method)
...
2.解决办法
一个非常常见的错误消息,它意味着地址(通常是端口号)已经被另一个应用程序使用。
要修复它,请更改端点端口号:
public static void main(String[] args) {
Endpoint.publish("http://localhost:1234/ws/hello", new WallStreetImpl());
}
参考
Java 质数示例
原文:http://web.archive.org/web/20230101150211/https://mkyong.com/java/java-prime-numbers-examples/
下面的 Java 示例将打印一个列表,列出所有的质数直到 1,000:
2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71
73 79 83 89 97 101 103 107 109 113 127 131 137 139 149 151 157 163 167 173
179 181 191 193 197 199 211 223 227 229 233 239 241 251 257 263 269 271 277 281
283 293 307 311 313 317 331 337 347 349 353 359 367 373 379 383 389 397 401 409
419 421 431 433 439 443 449 457 461 463 467 479 487 491 499 503 509 521 523 541
547 557 563 569 571 577 587 593 599 601 607 613 617 619 631 641 643 647 653 659
661 673 677 683 691 701 709 719 727 733 739 743 751 757 761 769 773 787 797 809
811 821 823 827 829 839 853 857 859 863 877 881 883 887 907 911 919 929 937 941
947 953 967 971 977 983 991 997
Total: 168
3 个 Java 示例:
- Java 8 流和 BigInteger
- 普通的旧爪哇咖啡
- 厄拉多塞算法的筛选
1.Java 8 流和 BigInteger
1.1 使用流。
PrintPrimeNumber.java
package com.mkyong.test;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import java.util.stream.Stream;
public class PrintPrimeNumber {
public static void main(String[] args) {
long count = Stream.iterate(0, n -> n + 1)
.limit(1000)
.filter(TestPrime::isPrime)
.peek(x -> System.out.format("%s\t", x))
.count();
System.out.println("\nTotal: " + count);
}
public static boolean isPrime(int number) {
if (number <= 1) return false; // 1 is not prime and also not composite
return !IntStream.rangeClosed(2, number / 2).anyMatch(i -> number % i == 0);
}
}
1.2 使用BigInteger::nextProbablePrime
Stream.iterate(BigInteger.valueOf(2), BigInteger::nextProbablePrime)
.limit(168)
.forEach(x -> System.out.format("%s\t", x));
或者针对 Java 9 的BigInteger.TWO
Stream.iterate(BigInteger.TWO, BigInteger::nextProbablePrime)
.limit(168)
.forEach(x -> System.out.format("%s\t", x));
2.普通的旧爪哇咖啡
没有更多的 Java 8 流,回到基本。
PrintPrimeNumber2.java
package com.mkyong.test;
import java.util.ArrayList;
import java.util.List;
public class PrintPrimeNumber2 {
public static void main(String[] args) {
List<Integer> collect = new ArrayList<>();
for (int i = 0; i < 1000; i++) {
if (isPrime(i)) {
collect.add(i);
}
}
for (Integer prime : collect) {
System.out.format("%s\t", prime);
}
System.out.println("\nTotal: " + collect.size());
}
private static boolean isPrime(int number) {
if (number <= 1) return false; // 1 is not prime and also not composite
for (int i = 2; i * i <= number; i++) {
if (number % i == 0) {
return false;
}
}
return true;
}
}
3.厄拉多塞筛
厄拉多塞算法的这个筛子很快就能找到所有的质数。
P.S 图片来自维基百科
概念是这样的:
- 循环 1#
p=2
=真,接下来 4,6,8,10,12,14…极限,所有+2 设置为假 - Loop 2#
p=3
= true,next 6{false,1#,ignore},9,12{false,1#,ignore},15,18{false,1#,ignore},21…limit,all +3 set false - 循环 3#
p=4
= {false,1#,ignore} - 循环 4#
p=5
=真,接下来的 10 个{假,1#,忽略},15 个{假,2#,忽略},20 个{假,1#,忽略}…全部+5 设置为假 - 循环 5#
p=6
= {false,1#,ignore} - 循环…直到极限,同样的想法。
- 收集所有真=质数。
PrintPrimeNumber3
package com.mkyong.test;
import java.util.Arrays;
import java.util.BitSet;
import java.util.LinkedList;
import java.util.List;
public class PrintPrimeNumber3 {
public static void main(String[] args) {
List<Integer> result = primes_soe_array(1000);
result.forEach(x -> System.out.format("%s\t", x));
System.out.println("\nTotal: " + result.size());
}
/**
* Sieve of Eratosthenes, true = prime number
*/
private static List<Integer> primes_soe(int limit) {
BitSet primes = new BitSet(limit);
primes.set(0, false);
primes.set(1, false);
primes.set(2, limit, true);
for (int p = 2; p * p <= limit; p++) {
if (primes.get(p)) {
for (int j = p * 2; j <= limit; j += p) {
primes.set(j, false);
}
}
}
List<Integer> result = new LinkedList<>();
for (int i = 0; i <= limit; i++) {
if (primes.get(i)) {
result.add(i);
}
}
return result;
}
// Some developers prefer array.
public static List<Integer> primes_soe_array(int limit) {
boolean primes[] = new boolean[limit + 1];
Arrays.fill(primes, true);
primes[0] = false;
primes[1] = false;
for (int p = 2; p * p <= limit; p++) {
if (primes[p]) {
for (int j = p * 2; j <= limit; j += p) {
primes[j] = false;
}
}
}
List<Integer> result = new LinkedList<>();
for (int i = 0; i <= limit; i++) {
if (primes[i]) {
result.add(i);
}
}
return result;
}
}
有人能帮忙把上面的算法转换成纯 Java 8 流吗?🙂
参考
Java–从资源文件夹中读取文件
在 Java 中,我们可以使用getResourceAsStream
或getResource
从类路径的resources
文件夹或根目录中读取一个或多个文件。
getResourceAsStream
方法返回一个InputStream
。
// the stream holding the file content
InputStream is = getClass().getClassLoader().getResourceAsStream("file.txt");
// for static access, uses the class name directly
InputStream is = JavaClassName.class.getClassLoader().getResourceAsStream("file.txt");
getResource
方法返回一个URL
并通常将其转换为一个File
;不在 JAR 文件中工作。
// get the file url, not working in JAR file.
URL resource = getClass().getClassLoader().getResource("file.txt");
if (resource == null) {
throw new IllegalArgumentException("file not found!");
} else {
// failed if files have whitespaces or special characters
//return new File(resource.getFile());
return new File(resource.toURI());
}
// for static access
// URL resource = JavaClassName.class.getClassLoader().getResource("fileName");
1.资源文件夹中的文件
1.1 查看src/main/resources
中的文件,稍后我们将访问这些文件并打印出文件内容。
src/main/resources/database.properties
datasource.url=jdbc:mysql://localhost/mkyong?useSSL=false
datasource.username=root
datasource.password=password
datasource.driver-class-name=com.mysql.jdbc.Driver
src/main/resources/json/file1.json
{
"name": "mkyong",
"age": 38
}
src/main/resources/json/file2.json
{
"name": "jack",
"age": 40
}
src/main/resources/json/sub/subfile1.json
{
"name": "sub",
"age": 99
}
1.2 默认情况下,Maven、Gradle 或 common Java practice 等构建工具会将所有文件从src/main/resources
复制到target/classes
或build/classes
的根目录下。因此,当我们试图从src/main/resources
读取文件时,我们从项目类路径的根目录读取文件。
1.3 下面是一个 JAR 文件结构。通常,resources
文件夹中的文件会复制到类路径的根目录。
Terminal
$ jar -tf target/example.jar
META-INF/MANIFEST.MF
META-INF/
json/
json/sub/
json/file2.json
json/sub/subfile1.json
json/file1.json
database.properties
com/
com/mkyong/
com/mkyong/io/
com/mkyong/io/utils/
//...
2.从资源文件夹中获取文件。
2.1 下面的例子演示了使用getResourceAsStream
和getResource
方法从resources
文件夹中读取文件json/file1.json
并打印出文件内容。
注
getResource
方法在 JAR 文件中不起作用。getResourceAsStream
方法在任何地方都有效。
FileResourcesUtils.java
package com.mkyong.io.utils;
import java.io.*;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.util.List;
public class FileResourcesUtils {
public static void main(String[] args) throws IOException {
FileResourcesUtils app = new FileResourcesUtils();
//String fileName = "database.properties";
String fileName = "json/file1.json";
System.out.println("getResourceAsStream : " + fileName);
InputStream is = app.getFileFromResourceAsStream(fileName);
printInputStream(is);
System.out.println("\ngetResource : " + fileName);
File file = app.getFileFromResource(fileName);
printFile(file);
}
// get a file from the resources folder
// works everywhere, IDEA, unit test and JAR file.
private InputStream getFileFromResourceAsStream(String fileName) {
// The class loader that loaded the class
ClassLoader classLoader = getClass().getClassLoader();
InputStream inputStream = classLoader.getResourceAsStream(fileName);
// the stream holding the file content
if (inputStream == null) {
throw new IllegalArgumentException("file not found! " + fileName);
} else {
return inputStream;
}
}
/*
The resource URL is not working in the JAR
If we try to access a file that is inside a JAR,
It throws NoSuchFileException (linux), InvalidPathException (Windows)
Resource URL Sample: file:java-io.jar!/json/file1.json
*/
private File getFileFromResource(String fileName) throws URISyntaxException{
ClassLoader classLoader = getClass().getClassLoader();
URL resource = classLoader.getResource(fileName);
if (resource == null) {
throw new IllegalArgumentException("file not found! " + fileName);
} else {
// failed if files have whitespaces or special characters
//return new File(resource.getFile());
return new File(resource.toURI());
}
}
// print input stream
private static void printInputStream(InputStream is) {
try (InputStreamReader streamReader =
new InputStreamReader(is, StandardCharsets.UTF_8);
BufferedReader reader = new BufferedReader(streamReader)) {
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}
}
// print a file
private static void printFile(File file) {
List<String> lines;
try {
lines = Files.readAllLines(file.toPath(), StandardCharsets.UTF_8);
lines.forEach(System.out::println);
} catch (IOException e) {
e.printStackTrace();
}
}
}
输出
Terminal
getResourceAsStream : json/file1.json
{
"name": "mkyong",
"age": 38
}
getResource : json/file1.json
{
"name": "mkyong",
"age": 38
}
2.2 现在,我们把项目打包成一个 JAR 文件,运行它;这一次,getResource
将失败并返回NoSuchFileException
或InvalidPathException
。我们无法通过资源 URL 读取 JAR 文件中的文件。
在 Linux (Ubuntu)上运行 JAR 文件,它抛出NoSuchFileException
。
Terminal
$ mvn clean package
$ java -jar target/java-io.jar
getResourceAsStream : json/file1.json
{
"name": "mkyong",
"age": 38
}
# for new File(resource.getFile());
getResource : json/file1.json
java.nio.file.NoSuchFileException: file:/home/mkyong/projects/core-java/java-io/target/java-io.jar!/json/file1.json
at java.base/sun.nio.fs.UnixException.translateToIOException(UnixException.java:92)
at java.base/sun.nio.fs.UnixException.rethrowAsIOException(UnixException.java:111)
at java.base/sun.nio.fs.UnixException.rethrowAsIOException(UnixException.java:116)
at java.base/sun.nio.fs.UnixFileSystemProvider.newByteChannel(UnixFileSystemProvider.java:219)
at java.base/java.nio.file.Files.newByteChannel(Files.java:370)
at java.base/java.nio.file.Files.newByteChannel(Files.java:421)
at java.base/java.nio.file.spi.FileSystemProvider.newInputStream(FileSystemProvider.java:420)
at java.base/java.nio.file.Files.newInputStream(Files.java:155)
at java.base/java.nio.file.Files.newBufferedReader(Files.java:2838)
at java.base/java.nio.file.Files.readAllLines(Files.java:3329)
at com.mkyong.io.utils.FileResourcesUtils.printFile(FileResourcesUtils.java:135)
at com.mkyong.io.utils.FileResourcesUtils.main(FileResourcesUtils.java:24)
# for new File(resource.toURI());
getResource : json/file1.json
Exception in thread "main" java.lang.IllegalArgumentException: URI is not hierarchical
at java.base/java.io.File.<init>(File.java:420)
at com.mkyong.io.utils.FileResourcesUtils.getFileFromResource(FileResourcesUtils.java:112)
at com.mkyong.io.utils.FileResourcesUtils.main(FileResourcesUtils.java:29)
在 Windows 上运行 JAR 文件,它抛出InvalidPathException
。
Terminal
$ mvn clean package
$ java -jar target/java-io.jar
getResourceAsStream : json/file1.json
{
"name": "mkyong",
"age": 38
}
getResource : json/file1.json
Exception in thread "main" java.nio.file.InvalidPathException:
Illegal char <:> at index 4: file:\C:\Users\mkyong\projects\core-java\java-io\target\java-io.jar!\json\file1.json
at java.base/sun.nio.fs.WindowsPathParser.normalize(WindowsPathParser.java:182)
at java.base/sun.nio.fs.WindowsPathParser.parse(WindowsPathParser.java:153)
at java.base/sun.nio.fs.WindowsPathParser.parse(WindowsPathParser.java:77)
at java.base/sun.nio.fs.WindowsPath.parse(WindowsPath.java:92)
at java.base/sun.nio.fs.WindowsFileSystem.getPath(WindowsFileSystem.java:229)
at java.base/java.io.File.toPath(File.java:2290)
at com.mkyong.io.utils.FileResourcesUtils.printFile(FileResourcesUtils.java:166)
at com.mkyong.io.utils.FileResourcesUtils.main(FileResourcesUtils.java:32)
这个例子使用 Maven 插件maven-jar-plugin
来创建 JAR 文件。
pom.xml
<!-- Make this jar executable -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<version>3.2.0</version>
<configuration>
<archive>
<manifest>
<addClasspath>true</addClasspath>
<mainClass>com.mkyong.io.utils.FileResourcesUtils</mainClass>
</manifest>
</archive>
</configuration>
</plugin>
3.从 resources 文件夹获取一个文件——单元测试
3.1 我们将测试资源放在文件夹src/test/resources
中进行单元测试。通常,测试资源中的文件会复制到target/test-classes
文件夹中。
src/test/resources/json/file1.json
{
"name": "unit test",
"age": 38
}
src/test/resources/database.properties
datasource.url=jdbc:mysql://localhost/test?useSSL=false
datasource.username=test
datasource.password=password
datasource.driver-class-name=com.mysql.jdbc.Driver
3.2 它的工作方式与我们从src/main/resources
读取文件的方式相同。我们使用相同的getResourceAsStream
和getResource
方法从src/test/resources
中读取文件。
FileResourcesTest.java
package com.mkyong.io;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import java.io.*;
import java.net.URISyntaxException;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.util.List;
// Unit test class
public class FileResourcesTest {
@DisplayName("Test loading a JSON file")
@Test
void loadJSONTest() {
String fileName = "json/file1.json";
ClassLoader classLoader = getClass().getClassLoader();
try (InputStream inputStream = classLoader.getResourceAsStream(fileName);
InputStreamReader streamReader = new InputStreamReader(inputStream, StandardCharsets.UTF_8);
BufferedReader reader = new BufferedReader(streamReader)) {
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}
}
@DisplayName("Test loading a properties file")
@Test
void loadPropTest() throws IOException, URISyntaxException {
String fileName = "database.properties";
ClassLoader classLoader = getClass().getClassLoader();
URL resource = classLoader.getResource(fileName);
if (resource == null) {
throw new IllegalArgumentException("file not found! " + fileName);
}
//File file = new File(resource.getFile());
File file = new File(resource.toURI());
List<String> lines = Files.readAllLines(file.toPath(), StandardCharsets.UTF_8);
lines.forEach(System.out::println);
}
}
输出
Terminal
{
"name": "unit test",
"age": 38
}
datasource.url=jdbc:mysql://localhost/test?useSSL=false
datasource.username=test
datasource.password=password
datasource.driver-class-name=com.mysql.jdbc.Driver
4.从资源文件夹中获取所有文件。(非 JAR 环境)
如果我们不知道确切的文件名,并且想要读取所有文件,包括 resources 文件夹中的子文件夹文件,我们可以使用 NIO Files.walk
轻松地访问和读取文件。
4.1 以下示例使用Files.walk
从文件夹src/main/resources/json
中读取所有文件:
FileResourcesUtils.java
package com.mkyong.io.utils;
import java.io.*;
import java.net.URISyntaxException;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.List;
import java.util.stream.Collectors;
public class FileResourcesUtils {
public static void main(String[] args) throws IOException {
FileResourcesUtils app = new FileResourcesUtils();
// read all files from a resources folder
try {
// files from src/main/resources/json
List<File> result = app.getAllFilesFromResource("json");
for (File file : result) {
System.out.println("file : " + file);
printFile(file);
}
} catch (URISyntaxException | IOException e) {
e.printStackTrace();
}
}
private List<File> getAllFilesFromResource(String folder)
throws URISyntaxException, IOException {
ClassLoader classLoader = getClass().getClassLoader();
URL resource = classLoader.getResource(folder);
// dun walk the root path, we will walk all the classes
List<File> collect = Files.walk(Paths.get(resource.toURI()))
.filter(Files::isRegularFile)
.map(x -> x.toFile())
.collect(Collectors.toList());
return collect;
}
// print a file
private static void printFile(File file) {
List<String> lines;
try {
lines = Files.readAllLines(file.toPath(), StandardCharsets.UTF_8);
lines.forEach(System.out::println);
} catch (IOException e) {
e.printStackTrace();
}
}
}
输出
Terminal
file : /home/mkyong/projects/core-java/java-io/target/classes/json/file1.json
{
"name": "mkyong",
"age": 38
}
file : /home/mkyong/projects/core-java/java-io/target/classes/json/file2.json
{
"name": "jack",
"age": 40
}
file : /home/mkyong/projects/core-java/java-io/target/classes/json/sub/subfile1.json
{
"name": "sub",
"age": 99
}
4.2 但是,例 4.1 中的标准Files.walk
不能直接访问 JAR 文件中的文件,尝试在 JAR 环境中运行例 4.1,它抛出FileSystemNotFoundException
。
Terminal
$ mvn clean package
$ java -jar target/java-io.jar
Exception in thread "main" java.nio.file.FileSystemNotFoundException
at jdk.zipfs/jdk.nio.zipfs.ZipFileSystemProvider.getFileSystem(ZipFileSystemProvider.java:169)
at jdk.zipfs/jdk.nio.zipfs.ZipFileSystemProvider.getPath(ZipFileSystemProvider.java:155)
at java.base/java.nio.file.Path.of(Path.java:208)
at java.base/java.nio.file.Paths.get(Paths.java:97)
at com.mkyong.io.utils.FileResourcesUtils.getAllFilesFromResource(FileResourcesUtils.java:128)
at com.mkyong.io.utils.FileResourcesUtils.main(FileResourcesUtils.java:35)
5.从资源文件夹中获取所有文件。(JAR 版本)
5.1 这个例子展示了如何通过FileSystems
和 URI jar:file:xxx.jar
来Files.walk
一个 JAR 文件中的一个文件夹。
这个想法是:
- File 使用
FileSystems
遍历 JAR 文件中的文件夹,并获取所有文件名,参见getPathsFromResourceJAR()
- 循环所有文件名,像例 2.1 一样访问并打印每个文件,见
getFileFromResourceAsStream()
。
FileResourcesUtils.java
package com.mkyong.io.utils;
import java.io.*;
import java.net.URI;
import java.net.URISyntaxException;
import java.nio.charset.StandardCharsets;
import java.nio.file.FileSystem;
import java.nio.file.FileSystems;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;
public class FileResourcesUtils {
public static void main(String[] args) throws IOException {
FileResourcesUtils app = new FileResourcesUtils();
// Sample 3 - read all files from a resources folder (JAR version)
try {
// get paths from src/main/resources/json
List<Path> result = app.getPathsFromResourceJAR("json");
for (Path path : result) {
System.out.println("Path : " + path);
String filePathInJAR = path.toString();
// Windows will returns /json/file1.json, cut the first /
// the correct path should be json/file1.json
if (filePathInJAR.startsWith("/")) {
filePathInJAR = filePathInJAR.substring(1, filePathInJAR.length());
}
System.out.println("filePathInJAR : " + filePathInJAR);
// read a file from resource folder
InputStream is = app.getFileFromResourceAsStream(filePathInJAR);
printInputStream(is);
}
} catch (URISyntaxException | IOException e) {
e.printStackTrace();
}
}
// get a file from the resources folder
// works everywhere, IDEA, unit test and JAR file.
private InputStream getFileFromResourceAsStream(String fileName) {
// The class loader that loaded the class
ClassLoader classLoader = getClass().getClassLoader();
InputStream inputStream = classLoader.getResourceAsStream(fileName);
// the stream holding the file content
if (inputStream == null) {
throw new IllegalArgumentException("file not found! " + fileName);
} else {
return inputStream;
}
}
// Get all paths from a folder that inside the JAR file
private List<Path> getPathsFromResourceJAR(String folder)
throws URISyntaxException, IOException {
List<Path> result;
// get path of the current running JAR
String jarPath = getClass().getProtectionDomain()
.getCodeSource()
.getLocation()
.toURI()
.getPath();
System.out.println("JAR Path :" + jarPath);
// file walks JAR
URI uri = URI.create("jar:file:" + jarPath);
try (FileSystem fs = FileSystems.newFileSystem(uri, Collections.emptyMap())) {
result = Files.walk(fs.getPath(folder))
.filter(Files::isRegularFile)
.collect(Collectors.toList());
}
return result;
}
// print input stream
private static void printInputStream(InputStream is) {
try (InputStreamReader streamReader = new InputStreamReader(is, StandardCharsets.UTF_8);
BufferedReader reader = new BufferedReader(streamReader)) {
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
输出
Terminal
$ java -jar target/java-io.jar
JAR Path :/C:/Users/mkyong/projects/core-java/java-io/target/java-io.jar
Path : /json/file2.json
filePathInJAR : json/file2.json
{
"name": "jack",
"age": 40
}
Path : /json/file1.json
filePathInJAR : json/file1.json
{
"name": "mkyong",
"age": 38
}
Path : /json/sub/subfile1.json
filePathInJAR : json/sub/subfile1.json
{
"name": "sub",
"age": 99
}
下载源代码
$ git 克隆https://github.com/mkyong/core-java
$ cd java-io