Open a tempfile with the registered application
October 9 2012 07:43:13 PM | Tags: Snippets Java
I use this often to create a temp file and open it with the according application. In this case, I created a pdf document as a print preview. To avoid 'save'-dialogs or forcing the user to walk through the filesystem, I directly open the document in Acrobat Reader.
To achive this I create a temp file using 'File'. This will result in a file named randomly, like 'prefix-2456730075766423086.pdf', created in %temp%. After my program terminated, the file will be deleted. This is a great functionality as it saves lot of time during development ;-)
But the real magic is done by 'Desktop'. It offers some actions like 'open', 'edit'; 'print', ... if available. To check this, first find out, if this platform supports 'Desktop' and hereafter, if 'open' action is available.
In this snippet, 'desktop.open(pdf);' will open Acrobat Reader, as this is the registered application for '.pdf'-files.
File pdf = File.createTempFile("prefix-", ".pdf");
pdf.deleteOnExit();
// create pdf file here...
if( Desktop.isDesktopSupported() ) {
Desktop desktop = Desktop.getDesktop();
if( desktop.isSupported( Desktop.Action.OPEN) ) {
desktop.open(pdf);
}
}
Comments [0]