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()