前言
最近调试lucene,想着以文本的形式输入json,文本中一行对应一个json文档,因为以前几乎没用过java,在网上找的资料总差那每一点意思,所以记录下研究的过程。
环境
java环境就不说了,随便一搜就有helloWorld
教程,做到这一步之后:
# json解析包
wget https://repo1.maven.org/maven2/org/json/json/20190722/json-20190722.jar
# 文件读取包
wget http://mirror.cogentco.com/pub/apache//commons/io/binaries/commons-io-2.6-bin.tar.gz
tar zxvf commons-io-2.6-bin.tar.gz
读
读的文件test1.json
如下所示:
{"name":"leo","age":18,"others":{"test1":1.1,"test2":"hello world"}}
代码如下所示ReadJson.java
:
import org.json.JSONObject;
import org.json.JSONException;
import java.io.File;
import java.io.IOException;
import org.apche.commons.io.FileUtils;
public class ReadJson {
public file = new File("test1.json");
try {
String content = FileUtils.readFileToString(file, "UTF-8");
JSONObject jsonObject = new JSONObject(content);
System.out.println("name: " + jsonObject.getString("name"));
System.out.println("test1: " + jsonObject.getJSONObject("others").getDouble("test1"));
}
catch(IOException e) {
e.printStackTrace();
}
}
如果输入文件是多个的,也就是我们真正的需求,读的文件test2.json
如下所示:
{"name":"leo","age":18,"others":{"test1":1.1,"test2":"hello world"}}
{"name":"alice","age":16,"others":{"test1":1.2,"test2":"nice to meet you"}}
代码如下所示ReadJsons.java
:
import org.json.JSONObject;
import org.json.JSONException;
import java.io.File;
import java.io.IOException;
import org.apche.commons.io.FileUtils;
public class ReadJsons {
public file = new File("test2.json");
LineIterator it = null;
try {
it = FileUtils.lineIterator(file, "UTF-8");
while (it.hasNext()) {
String content = it.nextLine();
JSONObject jsonObject = new JSONObject(content);
System.out.println("name: " + jsonObject.getString("name"));
System.out.println("test1: " + jsonObject.getJSONObject("others").getDouble("test1"));
}
}
catch(IOException e) {
e.printStackTrace();
}
finally {
LineIterator.closeQuietly(it);
}
}
run
javac -cp "<path>/json-20190722.jar:<path>/commons-io-2.6/commons-io-2.6.jar" ReadJson.java
java -cp "<path>/json-20190722.jar:<path>/commons-io-2.6/commons-io-2.6.jar" ReadJson