2015-01-15 81 views
0

下面的Java代碼的內存從JSON文件讀取值,使用freemarker模板的存儲JSON價值,並編寫新的結構與JSON鍵和值到文本文件並保存到提到的路徑,然後從上面提到的路徑文本文件中將被讀取,並將打印該文本文件到TSC打印機。我關心的是我要將該臨時讀寫文件存儲到內存中,關於此問題請問任何人都可以幫忙,如何存儲那個臨時文件到內存?如何寫/讀/使用Java

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" 

}] 
} 

Test.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 

回答

2

而不是將數據寫入一個文件,然後從文件中讀取它,使用一個ByteArrayOutputStream和一個ByteArrayInputStream(這意味着你的中間存儲機制是一個字節ar ray在內存中)。

FreeMarker的Template類使用Writer來編寫輸出。而不是使用一個FileWriter的,嘗試構建一個OutputStreamWriter:

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);  
+0

能否請你告訴我怎麼繼續ByteArrayOutputStream? – Code

+0

感謝賈森,我現在得到它,我還有一個問題,它有任何內存溢出或類似的問題時,它會存儲更多的數據,因爲我的JSON文件可能有更多的數據? – Code

+0

如果你有足夠的內存分配給java,它應該沒問題。你的JSON必須是巨大的才能引發問題,但它可能值得測試。 – Jason