-5

How can I run an external file in Java? Like opening a batch or a PDF file?

I want to add it to a jButton with Netbeans, so if somebody pushs on it, it will launch this file from a specified directory

Theres not a lot about this to find on the internet (except a web application, but it needs to be a file/batch/.exe ....

AS SAID its for Netbeans! Everytime I use those commands inside a Button Class:

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         

            // TODO add your handling code here:
            
        Runtime rt = Runtime.getRuntime();
        Process pr = rt.exec("msg * hello");
        
        
    }

I get an error for the line:

Process pr = rt.exec("msg * hello");

Which says:

unreported exception IOException; must be caught or declared to be thrown

Now how do I launch an external file?

E_net4
  • 27,810
  • 13
  • 101
  • 139
Advena
  • 1,664
  • 2
  • 24
  • 45

1 Answers1

2

The Runtime class can be used to do this. You can get an instance of this class via the static method Runtime.getRuntime(). In the Runtime class are several exec() methods that should be what you need.

Finally, you may consider the ProcessBuilder class more convenient depending on how complex your needs are.

Dan
  • 7,286
  • 6
  • 49
  • 114
President James K. Polk
  • 40,516
  • 21
  • 95
  • 125