How to execute cmd command through a netbeans project?

1.1k Views Asked by At

Currently I'm using this method:

import java.io.*;
import com.sun.speech.freetts.*;
import javax.swing.JOptionPane;

public class SO
{
    public void Open(String siteLink)
    {
        try
        {
            Process p = Runtime.getRuntime().exec("cmd /c start "+siteLink);
        }
        catch(Exception e)
        {
            JOptionPane.showMessageDialog(null,"Error"+e);
        }
    }
}

this was my java Class. And in the main frame source i typed :

SO run = new SO();
run.Open("file:///G:\\Abhijeet\\Videos\\");

this opens up the videos folder but this method is not launching the .exe files or windows applications.

I even tried using 'explorer =' , to launch my computers but nothing happened.

1

There are 1 best solutions below

0
On

I'm really not sure what you are trying to do, but the preferred way of opening a URL is probably Desktop#browse (Documentation: https://docs.oracle.com/javase/7/docs/api/java/awt/Desktop.html#browse(java.net.URI))

For starting a program, I would use Desktop#open (Documentation: https://docs.oracle.com/javase/7/docs/api/java/awt/Desktop.html#open(java.io.File))

Also, while you're at it - Do some research in command line injection. If any form of variable is used, the user can easily make it execute any command. Or you might accidently use a character that causes an error. If you still insist on using Runtime#exec in this case, see the one that takes a String[].
Then you would do new String[]{"cmd", "/c", "start", siteLink} most likely.