Friday, September 30, 2011

Check Directory is Empty

package org.best.example;
 
import java.io.File;

public class CheckEmptyDirectoryExample
{
    public static void main(String[] args)
    {   
     File file = new File("C:\\folder");
     if(file.isDirectory()){
         if(file.list().length>0){
             System.out.println("Directory is not empty!");
         }else{
            System.out.println("Directory is empty!");
         }
     }else{
         System.out.println("This is not a directory");
     }
    }
}

Why java is important to the Internet

The Internet helped catapult java to the forefront of programming, and java, in turn, has had a profound effect on the Internet. The reason for this is quite simple: Java expands the universe of objects that can move about freely in cyberspace. In a network, two very broad categories of objects are transmitted between the server and your personal computer: passive information and dynamic, active programs. For example, when you read your e-mail, you are viewing passive data. Even when you download a program, the program’s code is still only passive data. Even when you download a second type of object can be transmitted to your computer: a dynamic, self-executing program. Such a program is and the server yet initiates active agent on the client computer. For example, the server to display properly the data that the server is sending might provide a program.

As desirable as dynamic, networked programs are, they also present serious problems in the areas of security and portability. Prior to java, cyberspace was effectively closed to half the entities that now live there, as you will see, java addresses those concerns and, by doing so, has opened the door to an exciting new form of program: the applet.

Java Applets and Applications 

Java can be used to create two types of programs: applications and applets. An application is a program that runs on your computer, under the operating system of that computer. That is , an application created by java is more or less like one created using C or C++. When used to create applications, java is a not much different from any other computer language. Rather, it is java’s ability to create applets that makes it important. An applet is an application designed to be transmitted over the Internet and executed by a java-compatible Web browser. An applet is actually a tiny java program, dynamically downloaded across the network, just like an image, sound file, or video clip. The important difference is that an applet is an intelligent program, not just and animation or media file. In other words, and applet is a program that can react to user input and dynamically change not just run the same animation or sound over and over.

Security

As you are likely aware, every time that you download a “normal ” program, you are risking a viral infection. Prior to java, most users did not download executable programs frequently, and those who did scanned them for viruses prior to execution. Even so, most users still worried about the possibility of infection their systems with a virus. In addition to viruses, another type of maillicious program exists that must be guarded against. This type of program can gather private information, such as credit card numbers, bank account balances, and passwords, by searching the contents of your computer’s local file system, java answer both of these concerns by providing a “firewall” between a networked application and your computer.

Portability

Many types of computers and operating systems are in use throughout the world - and many are connected to the Internet. For programs to be dynamically downloaded to all the various types of platforms connected to the Internet, some means of generating portable executable code is needed. As you will soon see, the same mechanism that helps ensure security also helps create portability. Indeed, java’s solution to these two problems is both elegant and efficient.

Thursday, September 29, 2011

Copy Directory Content in Java

package org.best.example;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

public class CopyDirectoryExample
{
    public static void main(String[] args)
    {   
        File srcFolder = new File("c:\\best");
        File destFolder = new File("c:\\best\\example");

        //make sure source exists
        if(!srcFolder.exists()){

           System.out.println("Directory does not exist.");
           //just exit
           System.exit(0);

        }else{

           try{
            copyFolder(srcFolder,destFolder);
           }catch(IOException e){
            e.printStackTrace();
            //error, just exit
                System.exit(0);
           }
        }

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

    public static void copyFolder(File src, File dest)
        throws IOException{

        if(src.isDirectory()){

            //if directory not exists, create it
            if(!dest.exists()){
               dest.mkdir();
               System.out.println("Directory copied from "
                              + src + "  to " + dest);
            }

            //list all the directory contents
            String files[] = src.list();

            for (String file : files) {
               //construct the src and dest file structure
               File srcFile = new File(src, file);
               File destFile = new File(dest, file);
               //recursive copy
               copyFolder(srcFile,destFile);
            }

        }else{
            //if file, then copy it
            //Use bytes stream to support all file types
            InputStream in = new FileInputStream(src);
                OutputStream out = new FileOutputStream(dest);

                byte[] buffer = new byte[1024];

                int length;
                //copy the file content in bytes
                while ((length = in.read(buffer)) > 0){
                   out.write(buffer, 0, length);
                }

                in.close();
                out.close();
                System.out.println("File copied from " + src + " to " + dest);
        }
    }
}

What is the different between Set and List


Set and List explanation
  • Set – Stored elements in unordered or shuffles way, and does not allow duplicate values.
  • List – Stored elements in ordered way, and allow duplicate values.
Set and List Example
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class SetAndListExample
{
    public static void main( String[] args )
    {
        System.out.println("List example .....");
        List<String> list = new ArrayList<String>();
        list.add("1");
        list.add("2");
        list.add("3");
        list.add("4");
        list.add("1");

        for (String temp : list){
               System.out.println(temp);
        }

        System.out.println("Set example .....");
        Set<String> set = new HashSet<String>();
        set.add("1");
        set.add("2");
        set.add("3");
        set.add("4");
        set.add("1");
        set.add("2");
        set.add("5");

        for (String temp : set){
               System.out.println(temp);
        }       
    }
}
Output
List example .....
1
2
3
4
1
Set example .....
3
2
10
5
4
In Set, the stored values are in unordered way, and the duplicated value will just ignored.

Wednesday, September 28, 2011

Get Mac Address in Java JDK 1.6

package org.best.example;

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.UnknownHostException;

public class app{

   public static void main(String[] args){

    InetAddress ip;
    try {

        ip = InetAddress.getLocalHost();
       

        NetworkInterface network = NetworkInterface.getByInetAddress(ip);

        byte[] mac = network.getHardwareAddress();

        System.out.print("Current MAC address : ");

        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < mac.length; i++) {
            sb.append(String.format("%02X%s", mac[i], (i < mac.length - 1) ? "-" : ""));       
        }
        System.out.println(sb.toString());

    } catch (UnknownHostException e) {

        e.printStackTrace();

    } catch (SocketException e){

        e.printStackTrace();

    }

   }

}

Reverse loop versus Forward loop in Performance – Java


Forward Looping
Forward looping is loop from starting element and continues to the end of the elements. 0..1..2..3..End. Most of the time, may be i can said all the time we are using this type of looping method to loop through an array, List or collection.
for (int i=0; i< lList.size(); i++)
Reverse Looping
Reverse looping is loop from end of the element and continues to the starting elements. End..9..8..0. Most of the time, may be i can said all the time we are not using this type of looping method.
for (int i=lList.size()-1; i > 0; i--)
Performance Test
Here i create two tiny programs to use forward loop and reverse loop to traverse 15 millions of data, and display the elapse time in output.
1. Forward Looping
import java.util.Arrays;
import java.util.Date;
import java.util.List;

public class LoopTestForward {
  public static void main(String[] argv) {

          String sArray[] = createArray();

          //convert array to list
          List lList = Arrays.asList(sArray);
          int iListSize = lList.size();

          //Forward Loop Testing
          System.out.println("\n--------- Forward Loop --------\n");
          long lForwardStartTime = new Date().getTime();
          System.out.println("Start: " + lForwardStartTime);

          //for loop
          for (int i=0; i< iListSize; i++){
                 String stemp = (String)lList.get(i);
          }

          long lForwardEndTime = new Date().getTime();
          System.out.println("End: " + lForwardEndTime);

          long lForwardDifference = lForwardEndTime - lForwardStartTime;
          System.out.println("Forward Looping - Elapsed time in milliseconds: " + lForwardDifference);

          System.out.println("\n-------END-------");


  }

  static String [] createArray(){

          String sArray[] = new String [15000000];

          for(int i=0; i<15000000; i++)
                 sArray[i] = "Array " + i;

          return sArray;
  }
}
2. Reverse Looping
import java.util.Arrays;
import java.util.Date;
import java.util.List;

public class LoopTestReverse {
  public static void main(String[] argv) {

          String sArray[] = createArray();

          //convert array to list
          List lList = Arrays.asList(sArray);
          int iListSize = lList.size();

          //Reverse Loop Testing
          System.out.println("\n--------- Reverse Loop --------\n");
          long lReverseStartTime = new Date().getTime();
          System.out.println("Start: " + lReverseStartTime);

          //for loop
          for (int i=iListSize-1; i > 0; i--){
                 String stemp = (String)lList.get(i);
          }

          long lReverseEndTime = new Date().getTime();
          System.out.println("End: " + lReverseEndTime);

          long lReverseDifference = lReverseEndTime - lReverseStartTime;
          System.out.println("For - Elapsed time in milliseconds: " + lReverseDifference);

          System.out.println("\n-------END-------");

  }

  static String [] createArray(){

          String sArray[] = new String [15000000];

          for(int i=0; i<15000000; i++)
                 sArray[i] = "Array " + i;

          return sArray;
  }
}
D:\test>java -Xms1024m -Xmx1024m LoopTestFoward
D:\test>java -Xms1024m -Xmx1024m LoopTestReverse
Performance Test Result (in milliseconds)

Conclusion
The result show there’s not much different between forward and reverse looping in 1 million of data. However when data grow huge, the performance of reverse looping is slightly faster than forward looping around 15%.
May be you will question about who so stupid to load 1 million of data into a single List or Collection. Please imagine a multi-thread system environment, where 100k people concurrent access your “forward loop x 10″, it already over 1 million. Ya i know sometime the different is negligible, but i do believe believe “Reverse loop” is a good habit in programming , it can increase the performance. It’s sound weird …but performance show.

Tuesday, September 27, 2011

Get IP Address in Java

package org.best.example;

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.UnknownHostException;

public class app{

   public static void main(String[] args){

    InetAddress ip;
    try {

        ip = InetAddress.getLocalHost();
        System.out.println("Current IP address : " + ip.getHostAddress());

    } catch (UnknownHostException e) {

        e.printStackTrace();

    } catch (SocketException e){

        e.printStackTrace();

    }

   }

}

How to install java jdk on ubuntu (linux)


Installation Setup
1 ) Issue following command to find out current jdk version in apt-get
apt-cache search jdk
2 ) Install java JDK and JRE with apt-get install
apt-get install sun-java6-jdk sun-java6-jre
3 ) Ubuntu will auto download necessary file from web for installation.
Do you want to continue [Y/n]? y
Get:1 http://my.archive.ubuntu.com hardy/main java-common 0.28ubuntu3 [78.2kB]
Get:2 http://my.archive.ubuntu.com hardy/multiverse sun-java6-jre 6-06-0ubuntu1 [6334kB]
Get:3 http://my.archive.ubuntu.com hardy/main odbcinst1debian1 2.2.11-16build1 [66.2kB]
Get:4 http://my.archive.ubuntu.com hardy/main unixodbc 2.2.11-16build1 [289kB]
Get:5 http://my.archive.ubuntu.com hardy/multiverse sun-java6-bin 6-06-0ubuntu1 [27.3MB]
Get:6 http://my.archive.ubuntu.com hardy/multiverse sun-java6-jdk 6-06-0ubuntu1 [9625kB]
85% [6 sun-java6-jdk 3208002/9625kB 33%]

4) After installation done, jdk and jre will install at
/usr/lib/jvm/java-6-sun-1.6.0.06
5) Ubuntu help to create a java symbolic link and put in /usr/bin for shortcut access
4 ) type java -version, DONE !!
Post-Installation Setup
Set JAVA_HOME into environment variable
Copy following statement and append to /etc/profile or .bashrc file, make system set JAVA_HOME into system environment variable.
export JAVA_HOME="/usr/lib/jvm/java-6-sun-1.6.0.06"