I know it has been almost one year for this post :) but i am actually reposing again as an answer because i had this problem same as you Yuan
I have this text.txt file - I know this is not a valid Json array - but if you look, you will see that each line of this file is a Json object in its case alone.
{"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"}
Now I want to read each line of the above and parse the names "Sensor_ID" and "Date" into Json format. After long search, I have the following:
Try it and look on the console to see the result. I hope it helps.
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<JSONObject> json=new ArrayList<JSONObject>();
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();
}
}
}