This week's book giveaway is in the Servlets forum.
We're giving away four copies of Murach's Java Servlets and JSP and have Joel Murach on-line!
See this thread for details.
The moose likes Beginning Java and the fly likes Issue in launching a text file on Desktop. Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Issue in launching a text file on Desktop." Watch "Issue in launching a text file on Desktop." New topic

Issue in launching a text file on Desktop.

Manish Soin

Joined: Aug 01, 2011
Posts: 1
Hi I have an issue with following code.

This line in the code "try{Runtime.getRuntime().exec(st);}catch(IOException e1){System.out.println("Caught "+e1 );}" does not run Text file stored on Desktop in windows based computer.

Ulf Dittmer

Joined: Mar 22, 2005
Posts: 41034
What does it mean to "run" a text file? That's not executable content.

Ping & DNS - my free Android networking tools app
Rob Spoor

Joined: Oct 27, 2005
Posts: 19649

Welcome to the Ranch!

Manish Soin wrote:

First of all, there is no need whatsoever to create String st like that. You can simply use pa.
Second, you cannot execute any file, only executables and batch files. Anything else needs another application to run it.

Fortunately, you don't have to do any more hard work, using java.awt.Desktop that was introduced in Java 6. That same code snippet using the new class:
That will open the file with its default application. Yes, it's that simple these days.

OK, and now the more complex version that does some actual checking:
This uses the "magic" rundll32 url.dll,FileProtocolHandler command to use to execute the file with its default application. Of course this is only available on Windows.

Also, whenever you use Runtime.exec or ProcessBuilder, make sure to have read and understood When Runtime.exec() won't. It's an old article, but still very accurate. The only difference is that when you use ProcessBuilder with a redirected error stream, you don't need to read anything from p.getErrorStream().

Also, be aware of Concurrency in Swing. If you're not careful you may end up blocking the Event Dispatcher Thread, effectively making your entire user interface not respond to anything, including repaint requests from the operating system.
I agree. Here's the link:
subject: Issue in launching a text file on Desktop.
Similar Threads
How can i browse 3 files (same file format, exp: .txt) and process it ?
Saving an input.
actionPerformed not being called properly by child component
JTextArea append() not working?
How to keep formatting while reading files