利用org.json即可實現(xiàn)
一、基本思路
先利用IO流讀取txt文件,讀取每行內(nèi)容并轉為普通字符串(json形式的格式一定要正確),再將其轉為JSONObject對象,通過JSONObject對象來取不同類型的值。
txt文件內(nèi)容格式如下:
二、具體代碼
代碼如下(示例):
public static void main(String[] args) throws IOException {
String jsonpath="E:\\河南省鄉(xiāng)鎮(zhèn)點\\12.txt";
ReadGeojson.ReadGeojsonFile(jsonpath);
}
public static void ReadGeojsonFile(String jsonpath) throws IOException {
//讀取txt文件流
File file=new File(jsonpath);
FileInputStream fileInputStream = new FileInputStream(file);
InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream,"UTF-8");
BufferedReader bufReader = new BufferedReader(inputStreamReader);
try {
String line="";
//讀取每行內(nèi)容
StringBuffer sb=new StringBuffer();
while ((line=bufReader.readLine())!=null){
sb.append(line);
}
//去除空格
String sbreplace = sb.toString().replace(" ", "");
System.out.println(sbreplace);
//轉換成為JSONObject對象
JSONObject jsonObj =new JSONObject(sbreplace);
System.out.println(jsonObj.get("dataType"));
//第二層
Object attributes = jsonObj.get("attributes");
System.out.println(attributes);
JSONObject attributesObj =new JSONObject(attributes.toString());
System.out.println(attributesObj.get("userId"));
//數(shù)組形式
JSONArray geometry =(JSONArray) jsonObj.get("geometry");
System.out.println(geometry.get(0));
System.out.println(geometry.toString());
} catch (IOException e) {
e.printStackTrace();
}
bufReader.close();
}
結果如下
文章來源:http://www.zghlxwxcb.cn/news/detail-574692.html
總結
如果txt文件的格式不符合json格式要求的話,會在JSONObject jsonObj =new JSONObject(sbreplace);這一步出錯,錯誤一般為JSONObject text must begin with ‘{’ at 1 [character 2 line 1] 等。文章來源地址http://www.zghlxwxcb.cn/news/detail-574692.html
到了這里,關于java讀取并解析txt文件的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關文章,希望大家以后多多支持TOY模板網(wǎng)!