0

我嘗試使用基本信息在內存中加載文件,追加行並將結果包含到Zip文件中。在C#existes MemoryStream中,但在java中沒有。Java - 將文件加載爲模板+在內存中追加內容並管理字節[]

我的應用程序的上下文是加載stylesheet.css文件與預定義的樣式添加其他樣式,我得到dinamically。稍後我想將這些內容添加到zip條目中,並且我需要一個表示此內容的字節[]。

就目前而言,我有下一行,但我不知道是將它轉換爲字節]:

ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); 
File file = new File(classLoader.getResource("style.css").getFile()); 

OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream(file)); 
BufferedWriter writer = new BufferedWriter(osw); 

我試過,用ByteArrayOutputStream但我不能完成我的所有要求。

有什麼想法?爲了實現我的目標,我會選擇其他想法。我也在尋找CSSParser,但是我沒有看到,因爲我可以追加內容並獲取一個File文檔(byte [])來添加到我的zip文件中。

+0

這是什麼意思 「不能完成我的所有要求。」 ?你看到一個例外嗎?然後共享堆棧跟蹤。另請閱讀如何創建[最小化,完整和可驗證的示例](http://stackoverflow.com/help/mcve),以便這裏的人可以幫助我 – Ivan

+0

我的要求:1.在內存中加載文件,2.添加dinamically內容,也在內存中,3.轉換爲byte []添加到zip文件。 –

回答

0

Finnaly,我沒有找到我的問題的其他解決方案,將InputStream轉換爲ByteArrayOutputStream字節爲字節。

我創建了以下方法:

載入模板文件轉換成輸入流和轉換。

private ByteArrayOutputStream getByteArrayOutputStreamFor(String templateName) { 
    try { 
     ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); 
     InputStream inStream = classLoader.getResourceAsStream(templateName); //file into resources directory 
     ByteArrayOutputStream baos = Utils.toOutputStream(inStream); 

     return baos; 

    } catch (Exception e) { 
     String msg = String.format("erro to loaf filetemplate {%s}: %s", templateName, e.getMessage()); 
     throw new RuntimeException(msg, e.getCause()); 
    } 
} 

複製InputStream的到一個ByteArrayOutputStream逐字節

public static final ByteArrayOutputStream toOutputStream(InputStream inStream) { 
    try { 
     ByteArrayOutputStream outStream = new ByteArrayOutputStream(); 

     int byteReads; 
     while ((byteReads = inStream.read()) != -1) { 
      outStream.write(byteReads); 
     } 

     outStream.flush(); 
     inStream.close(); 

     return outStream; 

    } catch (Exception e) { 
     throw new RuntimeException("error message"); 
    } 
} 

最後,我附上文字ByteArrayOutputStream

ByteArrayOutputStream baosCSS = getByteArrayOutputStreamFor("templateName.css"); 
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(baosCSS)); 
writer.append("any text"); 
writer.flush(); 
writer.close(); 

byte[] bytes = baosCSS.toByteArray()