Showing posts with label System Utility Commands. Show all posts
Showing posts with label System Utility Commands. Show all posts

Friday, September 23, 2011

Open Browser in Java windows or Linux

package org.best.example;
 
public class StartBrowser {
 
  public static void main(String args[])
  {
 String url = "http://www.google.com";
 String os = System.getProperty("os.name").toLowerCase();
        Runtime rt = Runtime.getRuntime();
 
 try{
 
  if (os.indexOf( "win" ) >= 0)
{
// this doesn't support showing urls in the form of "page.html#nameLink" 
     rt.exec( "rundll32 url.dll,FileProtocolHandler " + url);
 
 } 
 else if (os.indexOf( "mac" ) >= 0) 
{
 
    rt.exec( "open " + url);
}
else if (os.indexOf( "nix") >=0 || os.indexOf( "nux") >=0) 
{
   // Do a best guess on unix until we get a platform independent way
   // Build a list of browsers to try, in this order.
   String[] browsers = {"epiphany", "firefox", "mozilla", "konqueror",
          "netscape","opera","links","lynx"};
 // Build a command string 
//which looks like "browser1 "url" || browser2 "url" ||..." 
StringBuffer cmd = new StringBuffer();
for (int i=0; i<browsers.length; i++)
  cmd.append( (i==0  ? "" : " || " ) + browsers[i] +" \"" + url + "\" ");
   rt.exec(new String[] { "sh", "-c", cmd.toString() });
}
else {
             return;
     }
       }catch (Exception e){
     return;
       }
      return;  
 
}

Thursday, June 9, 2011

How to Execute system commands in a Java Program

Most often in your Java programs you will find a need to execute system DOS commands. You can execute any system commands that are OS specific and then read the output of the system command from your Java program for further processing within the Java program.
This sample Java Program executes the 'dir' command reads the output of the dir command prints the results. This is just for understanding the concept, however, you may execute just about any command using this Runtime.getRuntime().exec() command.

package org.best.examples;
import java.io.*; 

public class doscmd 
{ 
public static void main(String args[]) 
{ 
try 
{ 
Process p=Runtime.getRuntime().exec("cmd /c dir"); 
p.waitFor(); 
BufferedReader reader=new BufferedReader(new InputStreamReader(p.getInputStream())); 
String line=reader.readLine(); 
while(line!=null) 
{ 
System.out.println(line); 
line=reader.readLine(); 
} 

} 
catch(IOException e1) {} 
catch(InterruptedException e2) {} 

System.out.println("Done"); 
} 
}