Running external command from Java & I/O operations


The below Java code, can be used to run any external command which may or may not take input from the console via Input redirection. This code has been tested on Unix/Linux only. Minor modifications may be required for other operating systems.

Uses: java Runner {command} {argument(s)} [-input] [input-file]
e.g: java Runner ‘ls -al’
e.g: java Runner java WordCount -input input.txt

 
/**
* @author shekhar
* @date   02/03/2010
* @description from java run any external command
**/
import java.io.*;

public class Runner{

        Runtime runtime;
        Process process;

        Runner(){
                runtime = Runtime.getRuntime();
        }

        /**
        * @param name of the file, input the the command
        **/

        void writeInput(String fileName){

                try{
                        OutputStream outputstream = process.getOutputStream();
                        OutputStreamWriter outputstreamwriter = new OutputStreamWriter(outputstream);
                        BufferedWriter bufferedwriter = new BufferedWriter(outputstreamwriter);
                        BufferedReader br = new BufferedReader(new FileReader(fileName));
                        String s = br.readLine();

                        /** writing the code into output stream of the process **/

                        while (s != null){
                                bufferedwriter.write(s);
                                s = br.readLine();
                        }
                        bufferedwriter.flush();
                        bufferedwriter.close();

                }catch(Exception e){
                        e.printStackTrace();
                }
        }
        /**
        * @param all the argument of command including command name, arguments, input file
        */

        void run( String[] args ){
                String cmd = "";
                String error = "";
                String output = "";
                int exitVal = -1;

                try{
                        /** parsing the arguments **/

                        for(int i=0;i<args.length;i++){
                                if( args[i].equals ( "-input" ) ){
                                        process = runtime.exec( cmd );
                                        writeInput ( args[ ++i ] );     // passing input file name if any needed;
                                }else{
                                        cmd = cmd + " "+ args[i];
                                        if( i == args.length -1 )
                                                process = runtime.exec( cmd );
                                }
                        }

                        process.waitFor();  // waiting the process to be over

                        exitVal = process.exitValue();

                        BufferedReader ebr = new BufferedReader( new InputStreamReader ( process.getErrorStream() ) );
                        String line = null;

                        while ( (line = ebr.readLine()) != null)
                                error += line+'\n';

                        BufferedReader ibr = new BufferedReader(new InputStreamReader ( process.getInputStream() ) );
                        while ( (line = ibr.readLine()) != null)
                                output += line+'\n';

                }catch(Exception e){
                        e.printStackTrace();
                }

                if( error.trim().length() > 0 ){
                        System.out.println("Error :"+error.trim());     // error if any during the excution of command
                }
                if( output.trim().length() > 0 ){
                        System.out.println("Output :"+output.trim());   // output of the excution of the command
                }

                System.out.println("Exit Value: "+exitVal);
        }

        public static void main(String[] args){
                try{
                        Runner runner = new Runner();
                        runner.run(args);
                }catch(Exception e){
                        e.printStackTrace();
                }
        }
}

Add/Remove Elements in HTML using Java Script


The code below is a simple example of Add, Remove elements in HTML file by updating DOM Tree.
<html>
    <head>
       <title> foo testing.. </title>
       <script>
       function addElement(num) {
           for( i=1; i <= num; i++) {
                  var element = document.getElementById('inputs');
                  var name = "input"+i;
                  var divId = "divid"+i;
                  var newdiv = document.createElement('div');
                  newdiv.setAttribute('id',divId);
                  newdiv .innerHTML = "Input"+i+": <input type='text' name='"+name+"'>";
                  newdiv .innerHTML +="&nbsp;<a href='#' onclick='removeElement(\""+divId+"\")'>Remove</a>";
                  element.appendChild(newdiv);
           }
       }
       function removeElement(divNum) {
               alert (divNum);
               var doc = document.getElementById('inputs');
               var olddiv = document.getElementById(divNum);
               doc.removeChild(olddiv);
           }
           </script>
   </head>
   <body>
        Enter the value: <input type='text' name='number' onblur='addElement(this.value)'>
        <div id = 'inputs'>
        <!-- Elements will be added here -->
        </div>
  </body>
</html>

Reading unicode from plain text/file


Reading Unicode characters from a raw text and want to use as Unicode character, require to unescape the character first and then can be used as Unicode.

The code below can be used for the same.

String unescape(String s) {
    int i=0,len=s.length();
    char c;
    StringBuffer sb = new StringBuffer(len);
    while (i<len) {
        c = s.charAt(i++);
        if (c=='\\') {
            if (i<len) {
               c = s.charAt(i++);
               if (c=='u'  || c == 'U' ) {
                   c = (char) Integer.parseInt(s.substring(i,i+4),16);
                   i += 4;
               } // add other cases here as desired...
           }
        } // fall through: \ escapes itself, quotes any character but u
       sb.append(c);
    }
return sb.toString();
}

Hello world!


Welcome to WordPress.com. This is your first post. Edit or delete it and start blogging!

Blog at WordPress.com.

%d bloggers like this: