Search code examples
filememoryoutputstreamfileoutputstreambytearrayoutputstream

Java - Load file as Template + append content in memory and manage byte[]


Im trying load a file in memory with a base information, append lines and include the result into a Zip file. In C# existes MemoryStream but, in java not.

the context of my application is load a stylesheet.css files with a pre-defined styles for add other styles that i get dinamically. Later i want add this content to a zip entry, and i need a byte[] that represent this content.

For the moment, i have the next lines, but i dont know as convert this to byte[]:

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

I tried, with ByteArrayOutputStream but i can't completed all my requirements.

Any idea? im opne to other ideas for get my goal. I looking for CSSParser too, but i didn't see as I can append content and get a File document (byte[]) for to add to my zip file.


Solution

  • Finnaly, i didn't find other solution for my problem that convert the InputStream to ByteArrayOutputStream byte to byte.

    I created the following methods:

    Load template file into Input Stream and convert.

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

    Copy the inputStream into a ByteArrayOutputStream byte to byte

    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");
        }
    }
    

    Finally, I append text to 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()