使用内存中的字节数组创建Java File对象(或等效对象)(无物理文件) [英] Create a Java File object (or equivalent) using a byte array in memory (without a physical file)

查看:639
本文介绍了使用内存中的字节数组创建Java File对象(或等效对象)(无物理文件)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在内存中创建一个Java File 对象(不创建物理文件),并用字节数组填充其内容。

I want to create a Java File object in memory (without creating a physical file) and populate its content with a byte array.

可以这样做吗?

想法是将它传递给Spring InputStreamSource 。我正在尝试下面的方法,但它返回说字节数组不包含文件名。。

The idea is to pass it to a Spring InputStreamSource. I'm trying the method below, but it returns saying "the byte array does not contain a file name.".

MimeMessage message = mailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(message);      
helper.setFrom("no-reply@example.com", "xyz");
helper.setTo(email);
helper.setText(body,true);
helper.setSubject(subject);
helper.addInline("cImage",
        new InputStreamResource(new ByteArrayInputStream(imageByteArr)));

mailSender.send(message);


推荐答案

你能粘贴完整的堆栈跟踪吗?没有内存文件这样的东西。使用ByteArrayInputStream就足够了。

Can you paste the full stack trace? There is no such thing as an "in memory" file. Using a ByteArrayInputStream should be sufficient.

您需要实现Resource#getFilename()。请尝试以下操作:

You need to implement Resource#getFilename(). Try the following:

helper.addInline("cImage", new ByteArrayResource(imageByteArr){
            @Override
            public String getFilename() {
                return fileName;
            }
        });

这篇关于使用内存中的字节数组创建Java File对象(或等效对象)(无物理文件)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆