Search code examples
javajakarta-eevaadinvaadin7

How do I load a FileResource into a byte array?


I have a file called data.dat that I would like to load into a byte[] in Vaadin. It is a data file that I need to load and then manipulate based on the user's input.

I tried:

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

The problem is that I don't know how to manipulate the resource to extract the byte[]. I see lots of information for how to put images and so on to the UI components, how to stream a user generated PDF, and so on, but I can't seem to find any examples on how to load your own data file that you then manipulate within code...


Solution

  • From the docs of vaadin you have:

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

    or

    DownloadStream getStream() 
        Gets resource as stream.
    

    And in DownloadStream:

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

    So you can easily operate on File or InputStream to read the contents of a FileResource

    For example in Java 8:

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