【问题标题】:How do I load a FileResource into a byte array?如何将 FileResource 加载到字节数组中?
【发布时间】:2015-07-16 23:01:34
【问题描述】:

我有一个名为 data.dat 的文件,我想将它加载到 Vaadin 中的 byte[] 中。这是一个数据文件,我需要加载并根据用户的输入进行操作。

我试过了:

String basepath = VaadinService.getCurrent().getBaseDirectory().getAbsolutePath();
FileResource resource = new FileResource(new File(basepath + MY_DATA_FILE));    

问题是我不知道如何操纵resource 来提取byte[]。我看到lots of information for how to put images and so on to the UI componentshow to stream a user generated PDF 等等,但我似乎找不到任何关于如何加载您自己的数据文件然后在代码中操作的示例...

【问题讨论】:

    标签: java jakarta-ee vaadin vaadin7


    【解决方案1】:

    来自 vaadin 的文档:

    java.io.File    getSourceFile() 
          Gets the source file.
    

    DownloadStream getStream() 
        Gets resource as stream.
    

    DownloadStream:

    java.io.InputStream getStream() 
          Gets downloadable stream.
    

    因此您可以轻松地对FileInputStream 进行操作以读取FileResource 的内容

    例如在 Java 8 中:

    byte[] bytes = Files.readAllBytes(Paths.get(resource.getSourceFile().getAbsolutePath()));
    

    【讨论】:

    • 如果您使用 Apache Commons-IO,我错过了 IOUtils.toByteArray(resource.getStream().getStream()) 中的 stream.stream。
    猜你喜欢
    • 1970-01-01
    • 2014-03-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-04
    • 1970-01-01
    相关资源
    最近更新 更多