【问题标题】:Java - Load file as Template + append content in memory and manage byte[]Java - 将文件作为模板加载+在内存中追加内容并管理字节[]
【发布时间】:2017-03-25 15:54:50
【问题描述】:

我正在尝试将带有基本信息的文件加载到内存中,添加行并将结果包含到 Zip 文件中。在 C# 中存在 MemoryStream,但在 java 中没有。

我的应用程序的上下文是加载一个带有预定义样式的 stylesheet.css 文件,以添加我动态获得的其他样式。稍后我想将此内容添加到一个 zip 条目中,并且我需要一个表示此内容的 byte[]。

目前,我有下一行,但我不知道将其转换为 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);

我尝试使用 ByteArrayOutputStream,但无法完成所有要求。

有什么想法吗?我愿意接受其他想法来实现我的目标。我也在寻找 CSSParser,但我没有看到,因为我可以附加内容并获取文件文档 (byte[]) 以添加到我的 zip 文件中。

【问题讨论】:

  • “无法完成我的所有要求”是什么意思?你看到一个例外吗?然后共享堆栈跟踪。另请阅读如何创建Minimal, Complete and Verifiable example,以便这里的人可以帮助您
  • 我的要求:1. 在内存中加载文件,2. 在内存中附加动态内容,3. 转换为 byte[] 以添加到 zip 文件。

标签: file memory outputstream fileoutputstream bytearrayoutputstream


【解决方案1】:

最后,我没有找到其他解决方案来解决我的问题,将 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()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-01-08
    • 2022-12-15
    • 2013-06-05
    • 1970-01-01
    • 1970-01-01
    • 2011-02-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多