Expose files to the system?

Hello!

I am trying to open a html file from an ActionPerformed of a jButton in the designer as follows:

File html = new File("Path/To/File");
if(Desktop.isDesktopSupported()){
     Desktop.getDesktop().browse(html.toURI());
}else{
     logger.info("Not supported");
}

The problem is, how can the system find the file? I have tried in the Designer’s Resource folder with no luck. I’m having the same problem with images to generate ImageIcons.

Thanks in advance,

Where is the file? In the module? If a resource in your module’s jar(s), you’ll have to extract the resource into a temporary file and pass that path to the external process.

The file would be in the module, yes. Would you mind elaborating on how to extract the temporary file?

You use the classloader for the class the file is alongside and open the resource as a stream:

https://docs.oracle.com/javase/8/docs/api/java/lang/ClassLoader.html#getResourceAsStream-java.lang.String-

Then I’d create and open a temporary file and use IOUtils.copy() to fill the temporary file.

For ImageIcon creation, I’d use findResource() to get the URL and then use the URL constructor. No need for a temporary file.

Okay, I think I got it. Thanks!

If anyone is ever wondering how to do this:

public void readAndOpenHTML()
            throws IOException {
        ClassLoader classLoader = this.getClass().getClassLoader();
        InputStream is = classLoader.getResourceAsStream("nameOftheResource.html");
        byte[] buffer = new byte[is.available()];
        is.read(buffer);
        is.close();
        Path tmpPath= Files.createTempFile("temporalName",".html");
        File html = tmpPath.toFile();
        OutputStream os = new FileOutputStream(html);
        os.write(buffer);;
        if (Desktop.isDesktopSupported()) {
            new Thread(()-> {
                try {
                    Desktop.getDesktop().browse(html.toURI());
                } catch (IOException e) {
                    //e.printStackTrace();
                    log.info("IOEX");
                    log.info(e.toString());
                }catch (Exception e){

                }
            }).start();
        } else {
            log.info("Desktop browser not suported");
        }

        os.close();

    }

1 Like

Consider caching the temporary file names to allow re-use if still there on future access.

Good point, thanks