我知道这个帖子已经差不多一年了:)但我实际上再次作为答案重新发布,因为我有这个问题和你一样
我有这个text.txt文件 – 我知道这不是一个有效的Json数组 – 但是如果你看一下,你会发现这个文件的每一行都是一个Json对象.
{"Sensor_ID":"874233","Date":"Apr 29,2016 08:49:58 Info Log1"}
{"Sensor_ID":"34234","Date":"Apr 29,2016 08:49:58 Info Log12"}
{"Sensor_ID":"56785","Date":"Apr 29,2016 08:49:58 Info Log13"}
{"Sensor_ID":"235657","Date":"Apr 29,2016 08:49:58 Info Log14"}
{"Sensor_ID":"568678","Date":"Apr 29,2016 08:49:58 Info Log15"}
现在我想读取上面的每一行,并将名称“Sensor_ID”和“Date”解析成Json格式.经过长时间的搜索,我有以下内容:
试一试,然后在控制台上查看结果.我希望它有所帮助.
package reading_file;
import java.io.*;
import java.util.ArrayList;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
public class file_read {
public static void main(String [] args) {
ArrayList json=new ArrayList();
JSONObject obj;
// The name of the file to open.
String fileName = "C:\\Users\\aawad\\workspace\\kura_juno\\data_logger\\log\\Apr_28_2016\\test.txt ";
// This will reference one line at a time
String line = null;
try {
// FileReader reads text files in the default encoding.
FileReader fileReader = new FileReader(fileName);
// Always wrap FileReader in BufferedReader.
BufferedReader bufferedReader = new BufferedReader(fileReader);
while((line = bufferedReader.readLine()) != null) {
obj = (JSONObject) new JSONParser().parse(line);
json.add(obj);
System.out.println((String)obj.get("Sensor_ID")+":"+
(String)obj.get("Date"));
}
// Always close files.
bufferedReader.close();
}
catch(FileNotFoundException ex) {
System.out.println("Unable to open file '" + fileName + "'");
}
catch(IOException ex) {
System.out.println("Error reading file '" + fileName + "'");
// Or we could just do this:
// ex.printStackTrace();
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}