The code is as follows:
Java code
- Import Java.io.BufferedReader;
- Import Java.io.File;
- Import Java.io.FileReader;
- Import Java.io.FileWriter;
- Import java.io.IOException;
- Import Java.io.PrintWriter;
- Import org.json.JSONException;
- Import Org.json.JSONObject;
- Public class Readandwritejson {
- /**
- * @param args
- * @throws jsonexception
- * @throws IOException
- */
- public static void Main (string[] args) throws Jsonexception, IOException {
- //TODO auto-generated method stub
- //String s = ReadFile ("./src/test.json");
- //System.out.println (s);
- Jsonobject jsonobject = new Jsonobject ();
- Jsonobject.put ("1", "one");
- Jsonobject.put ("2", "two");
- Jsonobject.put ("3", "three");
- Jsonobject.put ("4", "four");
- Jsonobject.put ("5", "five");
- Jsonobject.put ("6", "VI");
- Jsonobject.put ("7", "⑦");
- System.out.println (Jsonobject);
- WriteFile ("./src/test.json", jsonobject.tostring ());
- }
- public static void WriteFile (String filePath, String sets)
- throws IOException {
- FileWriter FW = New FileWriter (FilePath);
- PrintWriter out = new PrintWriter (FW);
- Out.write (sets);
- Out.println ();
- Fw.close ();
- Out.close ();
- }
- public static string ReadFile (string path) {
- File File = new file (path);
- BufferedReader reader = null;
- String laststr = "";
- try {
- reader = new BufferedReader (new FileReader (file));
- String tempstring = null;
- While ((tempstring = Reader.readline ()) = null) {
- Laststr = Laststr + tempstring;
- }
- Reader.close ();
- } catch (IOException e) {
- E.printstacktrace ();
- } finally {
- if (reader! = null) {
- try {
- Reader.close ();
- } catch (IOException E1) {
- }
- }
- }
- return laststr;
- }
- }
How to read and write JSON files