Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to open file with default application in SWT?

Tags:

java

swt

I have for example .pdf file (path to that file). How to open this file in default application (probably Acrobat Reader) from SWT application (for example on Button click) ?

like image 461
marioosh Avatar asked Mar 29 '12 23:03

marioosh


3 Answers

You should be able to use:

Program.launch(file);

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

Launches the operating system executable associated with the file or URL (http:// or https://). If the file is an executable then the executable is launched. Note that a Display must already exist to guarantee that this method returns an appropriate result.

Note that there are some peculiarities in Program.launch() (or at least there were, though these may have been fixed in more recent versions of the runtime.) I don't really remember the specifics of the bugs, but we do some checks to work around some issues:

  1. If you're on a Unix platform, and you're specifying an absolute path, there may be trouble opening that file. We prefix absolute paths with /. - so that /tmp/foo would be translated to /./tmp/foo - although I don't really remember the specifics of this bug any more than that.

  2. On Windows, if you're 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\"");

like image 195
Edward Thomson Avatar answered Nov 04 '22 00:11

Edward Thomson


Try Desktop.open:

Desktop.getDesktop().open(file);
like image 1
fgb Avatar answered Nov 04 '22 00:11

fgb


Maybe this can help to find a decision: we ran into PermGen space trouble upon call Desktop.open() - which is in AWTpackage - out of our SWT application.

So I would prefer Program.launch() over Desktop.open() in a SWT-environment.

like image 1
t3az0r Avatar answered Nov 03 '22 23:11

t3az0r