How to read and write JSON files

Source: Internet
Author: User
Tags readfile

The code is as follows:
Java code
  1. Import Java.io.BufferedReader;
  2. Import Java.io.File;
  3. Import Java.io.FileReader;
  4. Import Java.io.FileWriter;
  5. Import java.io.IOException;
  6. Import Java.io.PrintWriter;
  7. Import org.json.JSONException;
  8. Import Org.json.JSONObject;
  9. Public class Readandwritejson {
  10. /** 
  11. * @param args
  12. * @throws jsonexception
  13. * @throws IOException
  14. */
  15. public static void Main (string[] args) throws Jsonexception, IOException {
  16. //TODO auto-generated method stub
  17. //String s = ReadFile ("./src/test.json");
  18. //System.out.println (s);
  19. Jsonobject jsonobject = new Jsonobject ();
  20. Jsonobject.put ("1", "one");
  21. Jsonobject.put ("2", "two");
  22. Jsonobject.put ("3", "three");
  23. Jsonobject.put ("4", "four");
  24. Jsonobject.put ("5", "five");
  25. Jsonobject.put ("6", "VI");
  26. Jsonobject.put ("7", "⑦");
  27. System.out.println (Jsonobject);
  28. WriteFile ("./src/test.json", jsonobject.tostring ());
  29. }
  30. public static void WriteFile (String filePath, String sets)
  31. throws IOException {
  32. FileWriter FW = New FileWriter (FilePath);
  33. PrintWriter out = new PrintWriter (FW);
  34. Out.write (sets);
  35. Out.println ();
  36. Fw.close ();
  37. Out.close ();
  38. }
  39. public static string ReadFile (string path) {
  40. File File = new file (path);
  41. BufferedReader reader = null;
  42. String laststr = "";
  43. try {
  44. reader = new BufferedReader (new FileReader (file));
  45. String tempstring = null;
  46. While ((tempstring = Reader.readline ()) = null) {
  47. Laststr = Laststr + tempstring;
  48. }
  49. Reader.close ();
  50. } catch (IOException e) {
  51. E.printstacktrace ();
  52. } finally {
  53. if (reader! = null) {
  54. try {
  55. Reader.close ();
  56. } catch (IOException E1) {
  57. }
  58. }
  59. }
  60. return laststr;
  61. }
  62. }

How to read and write JSON files

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.