java - 如何使用java从内存中写入/读取内存

标签 java json memory printing freemarker

以下java代码从JSON文件中读取值,使用freemarker模板存储JSON值并用写入新结构JSON 键和值到文本文件并保存到提到的路径,之后将从提到的路径文本文件读取并将该文本文件打印到 TSC 打印机。我担心的是我想将该临时读/写文件存储到内存中,任何人都可以帮忙解决这个问题吗?如何将该临时文件存储到内存中?

Java 代码

public class JSONSimpleWritingToFileExample {  
public static void main (String[] args){

//  ************** Reading from JSON file **********

final String filePath = ("C:/Users//Desktop/333.json"); //JSON Path
FileReader reader = null;
try {
         reader = new FileReader(filePath);
         final JSONParser parser = new JSONParser();
         final JSONObject json = (JSONObject) parser.parse(reader);
         final JSONArray jsonUsers = (JSONArray) json.get("Booking");
         final Iterator<?> it = jsonUsers.iterator();
         while (it.hasNext())
         {
                    final JSONObject jsonUser = (JSONObject) it.next();
                    final String bookSrc = (String) jsonUser.get("Key1");
                    final String custName = (String) jsonUser.get("Key2");
                    final String custNum = (String) jsonUser.get("Key3");
                    final String custPName = (String) jsonUser.get("Key4");



// ********* Reading From Template *************                

         Configuration cfg = new Configuration();
try {
        //Load template from source folder
                    Template template = cfg.getTemplate("src/Test.ftl");  // Reading from Template path
        // Build the data-model
                    Map<String, Object> data = new HashMap<String, Object>();
                    data.put("Key1", ""+Value1);
                    data.put("Key2", ""+Value2); 
                    data.put("Key3", ""+Value3);
                    data.put("Key4", ""+Value4);

// Console output
                   Writer out = new OutputStreamWriter(System.out);
                   template.process(data, out);
                   out.flush();

// File output
                   Writer file = new FileWriter (new File("D:\\FTL_helloworld.txt")); // Writing text file path
                   template.process(data, file);
                   file.flush();
                   file.close();

// Reading Text file  & Printing Logic                  

                      FileInputStream textStream;
                  textStream = new FileInputStream("D:/FTL_helloworld.txt");
                  DocFlavor flavor = DocFlavor.INPUT_STREAM.AUTOSENSE;
                  DocAttributeSet das=new HashDocAttributeSet();
                  Doc mydoc = new SimpleDoc(textStream, flavor, das);
                  PrintRequestAttributeSet aset = new HashPrintRequestAttributeSet();
                  aset.add(OrientationRequested.PORTRAIT); 
                  @SuppressWarnings("unused")
                  PrinterJob pj = PrinterJob.getPrinterJob(); 
                  PrintService[] services = PrintServiceLookup.lookupPrintServices(flavor, aset);
                  PrintService defaultService = PrintServiceLookup.lookupDefaultPrintService();
              for (int i = 0; i < services.length; i++) 
                  {
                        System.out.println(services[i].getName());
                  }
             if(services.length == 0) 
                  {
                        if(defaultService == null) 
                  {
                                     //no printer found
                  } 
                 else {
                                    //print using default
                            DocPrintJob job = defaultService.createPrintJob();
                            job.print(mydoc, aset);
                      }
                      } 
                else {

                    PrintService service = ServiceUI.printDialog(null, 200, 200, services, defaultService, flavor, aset);
                    if (service != null)
                       {
                         DocPrintJob job = service.createPrintJob();
                         job.print(mydoc, aset);
                       }
                       }

 } catch (IOException e) {
   e.printStackTrace();
    } finally {
                if (reader != null) {
                try {
                       reader.close();
                     } catch (IOException e) {
                        e.printStackTrace();

                     }
                    }
                }
} } catch ( Exception e){
                 e.printStackTrace();
    }

 }
}

303 JSON 文件

{
"Booking": [ {
    "Key1":"Value1",
    "Key2":"Value2",
    "Key3":"Value3",
    "Key4":"Value4"

},
{
    "Key1":"Value1",
    "Key2":"Value2",
    "Key3":"Value3",
    "Key4":"Value4"

}]  
}

测试.ftl

Q799,B080+000
q831
rN
S4
D7
ZT
JF
OD,P
R24,0
N

X555,56,2,780,714
A771,73,1,1,2,1,N,"A  {0}"
A742,70,1,1,2,2,N,"   {1}({31})"
A765,450,1,1,2,2,N,"${Value1}"
A706,86,1,2,1,1,N,"${Value2}"
A682,86,1,2,1,1,N,"${Value3}"
A658,86,1,2,1,1,N,"${Value4}"
P1

最佳答案

不要将数据写入文件,然后从文件中读取数据,而是使用 ByteArrayOutputStream 和 ByteArrayInputStream (这意味着您的中间存储机制是字节数组)内存中)。

FreeMarker 的 Template 类使用 Writer 来写入输出。尝试构造一个 OutputStreamWriter,而不是使用 FileWriter:

ByteArrayOutputStream baos = new ByteArrayOutputStream();
OutputStreamWriter writer = new OutputStreamWriter(baos);
template.process(data, writer);
writer.close();

您可以检索数据:

byte[] savedData = baos.toByteArray();

然后读回:

ByteArrayInputStream bais = new ByteArrayInputStream(savedData);
DocFlavor flavor = DocFlavor.INPUT_STREAM.AUTOSENSE;
DocAttributeSet das = new HashDocAttributeSet();
Doc mydoc = new SimpleDoc(bais, flavor, das);    

关于java - 如何使用java从内存中写入/读取内存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27956942/

相关文章:

c - 为什么对 int 的引用只返回一个内存地址?

c# - 哈希表 - 内存不足

java - Hibernate不会自动创建表,但是当创建表时,它会将值插入表中

java - 实际上,我会使用鸭子类型还是控制反转?

java - 如何使用另一部手机的短信运行应用程序?

Java绘图程序

java - 输出html而不是json

java - 模拟Java中的内存使用

java - 将 LinkedHashMap<String,String> 转换为 Java 中的对象

c++ - Qt 5.0 Json编码