How to open a file using the default application in SWT?

I have, for example, a .pdf file (the path to this file). How to open this file in the default application (possibly Acrobat Reader) from the SWT application (for example, when a button is clicked)?

+6
source share
3 answers

You should be able to use:

 Program.launch(file); 

to open the file (using the default application or creator). From javadoc:

Runs the operating system executable file associated with the file or URL (http: // or https: //). If the file is executable, then the executable is launched. Note that a Display already exists to ensure that this method returns the appropriate result.

Please note that there are some features in Program.launch() (or at least there were, although they may have been fixed in later versions of the runtime.) I really don’t remember the specifics of the errors, but we do some checks for solutions to some problems:

  • If you are on a Unix platform and specify an absolute path, there may be a problem opening this file. We prefix absolute paths with /. - so that /tmp/foo will be translated to /./tmp/foo - although I really don't remember the specifics of this error anymore.

  • On Windows, if you are trying to open a UNC path - for example, \\server\bar - you need to wrap the string in double quotes. For example: Program.open("\"\\server\bar\"");

+10
source

Try Desktop.open:

 Desktop.getDesktop().open(file); 
+1
source

Perhaps this will help to find a solution: we encountered the PermGen space problem when calling Desktop.open() - which is located in AWTpackage - outside our SWT application.

Therefore, I would prefer Program.launch() over Desktop.open() in a SWT environment.

+1
source

Source: https://habr.com/ru/post/911996/


All Articles