json—如何使用java从内存中读写

6ovsh4lw  于 2021-06-30  发布在  Java
关注(0)|答案(1)|浏览(415)

下面的java代码正在从 JSON 文件,使用 freemarker 模板及其存储 JSON 重视并用 JSON 键和值保存到文本文件并保存到所述路径,然后从所述路径读取文本文件并将该文本文件打印到 TSC 我关心的是,我想把临时读写文件存储到内存中,有人能帮我一下吗,如何将临时文件存储到内存中?
java代码

  1. public class JSONSimpleWritingToFileExample {
  2. public static void main (String[] args){
  3. //**************Reading from JSON file**********
  4. final String filePath = ("C:/Users//Desktop/333.json"); //JSON Path
  5. FileReader reader = null;
  6. try {
  7. reader = new FileReader(filePath);
  8. final JSONParser parser = new JSONParser();
  9. final JSONObject json = (JSONObject) parser.parse(reader);
  10. final JSONArray jsonUsers = (JSONArray) json.get("Booking");
  11. final Iterator<?> it = jsonUsers.iterator();
  12. while (it.hasNext())
  13. {
  14. final JSONObject jsonUser = (JSONObject) it.next();
  15. final String bookSrc = (String) jsonUser.get("Key1");
  16. final String custName = (String) jsonUser.get("Key2");
  17. final String custNum = (String) jsonUser.get("Key3");
  18. final String custPName = (String) jsonUser.get("Key4");
  19. //*********Reading From Template*************
  20. Configuration cfg = new Configuration();
  21. try {
  22. //Load template from source folder
  23. Template template = cfg.getTemplate("src/Test.ftl"); // Reading from Template path
  24. // Build the data-model
  25. Map<String, Object> data = new HashMap<String, Object>();
  26. data.put("Key1", ""+Value1);
  27. data.put("Key2", ""+Value2);
  28. data.put("Key3", ""+Value3);
  29. data.put("Key4", ""+Value4);
  30. // Console output
  31. Writer out = new OutputStreamWriter(System.out);
  32. template.process(data, out);
  33. out.flush();
  34. // File output
  35. Writer file = new FileWriter (new File("D:\\FTL_helloworld.txt")); // Writing text file path
  36. template.process(data, file);
  37. file.flush();
  38. file.close();
  39. // Reading Text file & Printing Logic
  40. FileInputStream textStream;
  41. textStream = new FileInputStream("D:/FTL_helloworld.txt");
  42. DocFlavor flavor = DocFlavor.INPUT_STREAM.AUTOSENSE;
  43. DocAttributeSet das=new HashDocAttributeSet();
  44. Doc mydoc = new SimpleDoc(textStream, flavor, das);
  45. PrintRequestAttributeSet aset = new HashPrintRequestAttributeSet();
  46. aset.add(OrientationRequested.PORTRAIT);
  47. @SuppressWarnings("unused")
  48. PrinterJob pj = PrinterJob.getPrinterJob();
  49. PrintService[] services = PrintServiceLookup.lookupPrintServices(flavor, aset);
  50. PrintService defaultService = PrintServiceLookup.lookupDefaultPrintService();
  51. for (int i = 0; i < services.length; i++)
  52. {
  53. System.out.println(services[i].getName());
  54. }
  55. if(services.length == 0)
  56. {
  57. if(defaultService == null)
  58. {
  59. //no printer found
  60. }
  61. else {
  62. //print using default
  63. DocPrintJob job = defaultService.createPrintJob();
  64. job.print(mydoc, aset);
  65. }
  66. }
  67. else {
  68. PrintService service = ServiceUI.printDialog(null, 200, 200, services, defaultService, flavor, aset);
  69. if (service != null)
  70. {
  71. DocPrintJob job = service.createPrintJob();
  72. job.print(mydoc, aset);
  73. }
  74. }
  75. } catch (IOException e) {
  76. e.printStackTrace();
  77. } finally {
  78. if (reader != null) {
  79. try {
  80. reader.close();
  81. } catch (IOException e) {
  82. e.printStackTrace();
  83. }
  84. }
  85. }
  86. } } catch ( Exception e){
  87. e.printStackTrace();
  88. }
  89. }
  90. }

303 json文件

  1. {
  2. "Booking": [ {
  3. "Key1":"Value1",
  4. "Key2":"Value2",
  5. "Key3":"Value3",
  6. "Key4":"Value4"
  7. },
  8. {
  9. "Key1":"Value1",
  10. "Key2":"Value2",
  11. "Key3":"Value3",
  12. "Key4":"Value4"
  13. }]
  14. }

测试.ftl

  1. Q799,B080+000
  2. q831
  3. rN
  4. S4
  5. D7
  6. ZT
  7. JF
  8. OD,P
  9. R24,0
  10. N
  11. X555,56,2,780,714
  12. A771,73,1,1,2,1,N,"A {0}"
  13. A742,70,1,1,2,2,N," {1}({31})"
  14. A765,450,1,1,2,2,N,"${Value1}"
  15. A706,86,1,2,1,1,N,"${Value2}"
  16. A682,86,1,2,1,1,N,"${Value3}"
  17. A658,86,1,2,1,1,N,"${Value4}"
  18. P1
5hcedyr0

5hcedyr01#

使用 ByteArrayOutputStream 和一个 ByteArrayInputStream (这意味着您的中间存储机制是内存中的字节数组)。
freemarker的模板类使用 Writer 写入输出。请尝试构造outputstreamwriter,而不是使用filewriter:

  1. ByteArrayOutputStream baos = new ByteArrayOutputStream();
  2. OutputStreamWriter writer = new OutputStreamWriter(baos);
  3. template.process(data, writer);
  4. writer.close();

您可以检索数据:

  1. byte[] savedData = baos.toByteArray();

然后重新阅读:

  1. ByteArrayInputStream bais = new ByteArrayInputStream(savedData);
  2. DocFlavor flavor = DocFlavor.INPUT_STREAM.AUTOSENSE;
  3. DocAttributeSet das = new HashDocAttributeSet();
  4. Doc mydoc = new SimpleDoc(bais, flavor, das);
展开查看全部

相关问题