Java 7 - try-with-resources

In earlier tutorials we have seen couple of Java 7 features like Underscore in numeric literals, Switch Case with non-primitive data-type and Exception handling with multi-catch.

In this tutorial we will see about try-with-resources is a one of the fine feature added in Java 7.
 

For example if we need to allocate a resource for file handling or database connectivity then we need to explicitly close the resource which we have opened in our try block. In those cases it will be tedious to handle lot of resource management manually. In some of the cases we will have try with finally block where we will check for the resource closing. No matter whether the to resource has allocated or not finally block will be executed automatically for all time. Below is the simple example from earlier Java 7 as how we used to handle resources by using file handling.
 



public class MyOldFileHandling {
    public static void main(String[] arg){
        FileInputStream fstream = null;
        DataInputStream istream = null;
        BufferedReader breader = null;
        try {            
            fstream = new FileInputStream("test.txt");
            istream = new DataInputStream(fstream);
            breader = new BufferedReader(new InputStreamReader(istream));
            String line;
            while ((line = breader.readLine()) != null) {
                System.out.println (line);
            }            
        } catch (IOException ex) {
            ex.printStackTrace();
        } finally{
            try{
                /* 
                 * Explicitly all resources need to be closed in 
                 * earlier java versions 
                */

                if(fstream != null)fstream.close();
                if(istream != null)istream.close();
                if(breader != null)breader.close();
            }catch(IOException ioe){
                ioe.printStackTrace();;
            }
        }
    }
}



In above program we can see explicitly programmers need to handle resource closing under finally block, whether resource has or not finally block will be executed compulsory. 

But in Java 7 onwards try-catch-resource feature introduced and programmer need not to worry about resource management once when we add resource in try statement as like bellow.
 



try(FileInputStreamfstream = new FileInputStream("test.txt")) {
.
.
}



Above statement will have same functionality of FileInputStream of our above program. Where as here resource closing close() method will be automatically called once try block completed. Even we can multiple resource under single try block as like below.
 



try(FileInputStreamfstream = new FileInputStream("test.txt");
    DataInputStream istream = new DataInputStream(fstream);
    BufferedReader breader = new BufferedReader(new InputStreamReader(istream))) {
.
.
}

Below example will show same above program will be handled using try-with-resource using Java 7.
 



public class MyNewFileHandling {
        public static void main(String[] arg){
        
        try (FileInputStream fstream = new FileInputStream("test.txt");            
             DataInputStream istream = new DataInputStream(fstream);
             BufferedReader breader = new BufferedReader(new InputStreamReader(istream))) {            
            
            String line;
            while ((line = breader.readLine()) != null) {
                System.out.println (line);
            }            
        } catch (IOException ex) {
            ex.printStackTrace();
        } 
    }
}




 

Drawing image border using Java Code





In our last tutorial we have seen how to re-size image using Java code. In this tutorial we will see how to draw a border in the image using Java code.



import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;

public class ImageBorder {

    public static void main(String[] args) {
        new ImageBorder().createBorderImage("e:\\tree.jpg", "e:\\tree_border.jpg");
    }
    
    public void createBorderImage(String oriImgUrl, String saveLocFilePath){
        try {
            int borderColor = 0x99FF0000; //Red color
            BufferedImage image = ImageIO.read(new File(oriImgUrl));
            for(int i=0;i < image.setRGB(0, i, borderColor);
                image.setRGB(image.getWidth()-1, i, borderColor);
            }
            for(int i=0;i < image.setRGB(i, 0, borderColor);
                image.setRGB(i, image.getHeight()-1, borderColor);
            }
            ImageIO.write(image, "png"new File(saveLocFilePath));
            
        } catch (IOException ioe) {
            ioe.printStackTrace();
        }
    }
}






Image resizing using Java code




We will see how to re-size image using Java program. Below program will explains you about resizing image using Java code. Method resizeMyImage() will take necessary parameters like re-size image name, original image and resize image sizes (width and height).



import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;

public class ImageResize {
    public static void main(String[] args) {
        // resize_image_name, original_image, resize_image_sizes 
        new ImageResize().resizeMyImage("e:\\rat_resized.jpg", "e:\\rat.jpg", "200", "93");
    }
    
    private void resizeMyImage(String resizeImg, String filePath, String w, String h){
        if(new File(filePath).exists()){
            imageResize(filePath, Integer.parseInt(w) , Integer.parseInt(h), resizeImg);
            System.out.println("Resize completed....");
        }else{
            System.out.println("Original file not exist....");
        }        
    }
    
    public void imageResize(String oriImgUrl, int width, int heigth, String saveLocFilePath){
        try {            
            File f = new File(oriImgUrl);
            BufferedImage image = ImageIO.read(f);
            BufferedImage resizeImage = resize(image, width, heigth);
            ImageIO.write(resizeImage, "jpg"new File(saveLocFilePath));            
        } catch (IOException ioe) {
            ioe.printStackTrace();
        }
    }
    
    private static BufferedImage resize(BufferedImage image, int width, int height) {
        BufferedImage resizedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        Graphics2D g = resizedImage.createGraphics();
        g.drawImage(image, 0, 0, width, height, null);
        g.dispose();
        return resizedImage;
    }
}






 

Sending SMS through JAVA code

 
In this tutorial we will see about sending SMS through Java code in India. For this first we need to chose some SMS gateway for sending SMS across India and other countries. I have chose www.SMSZone.in for this and will see small example for sending SMS.

Steps to get subscribed:
  • 1. For subscribing we need to provide registered Mobile no. and company / personal details. 
  • 2. Once subscribed need to decide whether we are going to use SMS for promotional or non-promotional activities. 
  • 3. Based on that we need decide our tariff plan and SMS template formats. 
  • 4. Next we need to chose the SenderId for SMS, like JDISCO (only 6 letters are allowed)
  • 5. Next you chose any language for sending SMS like Java, .NET, PHP etc.,


Lets see small Java code for sending SMS by using above SMS gateway.



public class SendSMS {
  
  // SMS Gateway API
  static String SMSApi = "http://www.smszone.in/sendsms.asp?page=SendSmsBulk&username=91XXXX12XXXX&password=XXXX&number=<PHONE>&message=<MSG>&SenderId=JDISCO";
  
  //List of mobile numbers to send SMS
  static String phoneNos = "91XXXX54XXXX, 91XXXX56XXXX";
  
  // SMS text
  static String smsText = "Hi All, Welcome to JavaDiscover";
    
  public static void main(String[] args) {
    try{
      String url = SMSApi.replace("<PHONE>", phoneNos).replace("<MSG>", smsText).replaceAll(" ""%20");
      String smsApiResponse = sendMySMS(url);
      System.out.println(smsApiResponse);
    }catch (Exception e) {
      e.printStackTrace();
    }
  }
  
  public static String sendMySMS(String url){
    StringBuilder output = new StringBuilder();
    try{
      URL hp = new URL(url);
      System.out.println(url);
      URLConnection hpCon = hp.openConnection()
      BufferedReader in = new BufferedReader(new InputStreamReader(hpCon.getInputStream()));
      String inputLine;
      while ((inputLine = in.readLine()) != null)
        output.append(inputLine);
      in.close();
    }catch (Exception e) {
      e.printStackTrace();
    }
    return output.toString();
  }
}




Change you Username, password, phone number and Senderid accordingly. 





Using Java TreeMap

 
Today we will see about one of the important interface in Java called Map interface. Map interface and derived classes are in java.util.Map package and Map uses simple data structure that contains Key and Value. Always key must be unique Object and its uses Hashing to identify the correct Key and corresponding Value in the Sequential array (Used to call as bucket). 

Under Map interface lot of derived classes and lets see TreeMap in this tutorial.

TreeMap:
       TreeMap is an important class which implements the Map interface. As same as HashMap TreeMap also uses the Key/ Value to store the data in a sorted order. TreeMap can be created in 2 ways as natural sorted order or custom sorted order by using Comparator. Below we will see small examples for all these types.


Example: TreeMap using natural sort.


public class TreeMapTest {
 public static void main(String[] args) {
  TreeMap<String, String> map = new TreeMap<String, String>();
  map.put("4", "Delhi");
  map.put("3", "Mumbai");
  map.put("5", "Chennai");
  map.put("1", "Culcutta");
  map.put("2", "Bangalore");
  
  // Sorted TreeMap
  System.out.println("Sorted TreeMap values....");
  for (Map.Entry<String, String> entry : map.entrySet()) {
   System.out.println("KEY : "+entry.getKey() +" - VALUE : "+entry.getValue());
  }
  
  // Getting size TreeMap
  System.out.println("\nSize of TreeMap :: "+map.size());
  
  // Contains Key in TreeMap
  System.out.println("\nKey Contains (15) : "+map.containsKey("15"));
  System.out.println("Key Contains (4) : "+map.containsKey("4"));
    
  // Contains Value in TreeMap
  System.out.println("\nValue Contains (Delhi) : "+map.containsValue("Delhi"));
  System.out.println("Value Contains (Ney York) : "+map.containsValue("New York"));
    
  // Getting Reversing TreeMap
  NavigableMap<String, String> revMap = map.descendingMap();
  System.out.println("\nReverse TreeMap values....");
  for (Map.Entry<String, String> entry : revMap.entrySet()) {
   System.out.println("KEY : "+entry.getKey() +" - VALUE : "+entry.getValue());
  }
  
  // Get sub portion of map to subMap
  SortedMap<String, String> subMap = map.subMap("2","4");
  System.out.println("\nSub portion TreeMap values....");
  for (Map.Entry<String, String> entry : subMap.entrySet()) {
   System.out.println("KEY : "+entry.getKey() +" - VALUE : "+entry.getValue());
  }
  
  // Getting first Key and Entry in TreeMap
  System.out.println("\nFirst Key in TreeMap : "+map.firstKey());
  System.out.println("First Entry in TreeMap : "+map.firstEntry());
  
  // Getting last Key and Entry in TreeMap
  System.out.println("\nLast Key in TreeMap : "+map.lastKey());
  System.out.println("Last Entry in TreeMap : "+map.lastEntry());
  
  // Removing data from TreeMap
  map.remove("3");
  System.out.println("\nTreeMap size after removing 1 element : "+map.size());
  
  // Checking TreeMap is empty or not
  System.out.println("\nTreeMap empty or not : "+map.isEmpty());
  
  // Clearing complete TreeMap
  map.clear();
  System.out.println("\nTreeMap size after clearing all values : "+map.size());
  System.out.println("TreeMap empty or not : "+map.isEmpty());
  
 }
}



OUTPUT:


Sorted TreeMap values....
KEY : 1 - VALUE : Culcutta
KEY : 2 - VALUE : Bangalore
KEY : 3 - VALUE : Mumbai
KEY : 4 - VALUE : Delhi
KEY : 5 - VALUE : Chennai

Size of TreeMap :: 5

Key Contains (15) : false
Key Contains (4) : true

Value Contains (Delhi) : true
Value Contains (Ney York) : false

Reverse TreeMap values....
KEY : 5 - VALUE : Chennai
KEY : 4 - VALUE : Delhi
KEY : 3 - VALUE : Mumbai
KEY : 2 - VALUE : Bangalore
KEY : 1 - VALUE : Culcutta

Sub portion TreeMap values....
KEY : 2 - VALUE : Bangalore
KEY : 3 - VALUE : Mumbai

First Key in TreeMap : 1
First Entry in TreeMap : 1=Culcutta

Last Key in TreeMap : 5
Last Entry in TreeMap : 5=Chennai

TreeMap size after removing 1 element : 4

TreeMap empty or not : false

TreeMap size after clearing all values : 0
TreeMap empty or not : true



In above example we can see automatically TreeMap sorted and also other methods in TreeMap class.

Next we will see simple example using custom sorting using Comparator.

Example: TreeMap using custom sort - Comparator.




public class TreeMapUsingCustomComparator {
 
 public static void main(String a[]){
  TreeMap<Worker,String> map = new TreeMap<Worker, String>(new MyNameComp());
  map.put(new Worker("david",5000), "david");
  map.put(new Worker("joy",2000), "joy");
  map.put(new Worker("abel",7000), "abel");
  map.put(new Worker("ruby",9000), "ruby");
  
  for (Map.Entry<Worker, String> entry : map.entrySet()) {
   System.out.println("KEY : "+ entry.getKey() +" \t VALUE : "+entry.getValue());
  }
 }
}




public class Worker{
    
    private String name;
    private int salary;
    
    public Worker(String name, int salary){
        this.name = name;
        this.salary = salary;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public int getSalary() {
        return salary;
    }
    public void setSalary(int salary) {
        this.salary = salary;
    }
    public String toString(){
        return "("+this.name+":"+this.salary+")";
    }
}




public class MyNameComp implements Comparator<Worker>{
    public int compare(Worker obj1, Worker obj2) {
        return obj1.getName().compareTo(obj2.getName());
    }
}



OUTPUT: 


KEY : (abel:7000)   VALUE : abel
KEY : (david:5000)   VALUE : david
KEY : (joy:2000)   VALUE : joy
KEY : (ruby:9000)   VALUE : ruby





Using keySet(), entrySet() and values() methods in HashMap

Today we will see about using keySet(), value() and entrySet() methods in HashMap. Basically all these methods will be used to get the list of keys and values from HashMap. Lets see each one separately how its used in Java.
  • keySet() method is used to get only the list of keys in HashMap.
  • value() method is used to get only the list of values in HashMap.
  • entrySet() method is used to get both key and values from the HashMap.

Below is a simple example program which will explain about using all these 3 methods.

 


public class HashMapTest {
 
 public static void main(String[] args) {
 
    Map<String, String> hm = new HashMap<String, String>();
    hm.put("key1", "Bangalore");
    hm.put("key3", "India");
    hm.put("key2", "Mumbai");
    hm.put("key5", "New Delhi");
    hm.put("key4", "Chennai");
    
    new HashMapTest().getOnlyKeyList(hm);
    new HashMapTest().getOnlyValueList(hm);
    new HashMapTest().getBothKeyValue(hm);    
 }
 
 // Fetching only Keys by using keySet() method
 public void getOnlyKeyList(Map<String, String> hm){
  Iterator<String> itr = ((Set<String>) hm.keySet()).iterator();
  System.out.println("USING keyset() :::::::::::: ");
  while(itr.hasNext()){
   String key = itr.next();
   System.out.println("KEY : "+key);
  }
 }
 
 // Fetching only values by using value() method
 public void getOnlyValueList(Map<String, String> hm){
  Iterator<String> itr = hm.values().iterator();
  System.out.println("\n\nUSING value() :::::::::::: ");
  while(itr.hasNext()){
   String value = itr.next();
   System.out.println("VALUE : "+value);
  }
 }
 
 // Fetching both keys and values using entrySet() method
 public void getBothKeyValue(Map<String, String> hm){
  Iterator <Map.Entry<String,String>>entryset = hm.entrySet().iterator();
  System.out.println("\n\nUSING entryset() :::::::::::: ");
  while(entryset.hasNext()){
   Map.Entry <String,String>entry=entryset.next();
   String key = entry.getKey();
   String value = entry.getValue();
   System.out.println("KEY : "+key +" - VALUE : "+value);
  }
 }
}



OUTPUT:



USING keyset() :::::::::::: 
KEY : key1
KEY : key3
KEY : key5
KEY : key2
KEY : key4


USING value() :::::::::::: 
VALUE : Bangalore
VALUE : India
VALUE : New Delhi
VALUE : Mumbai
VALUE : Chennai


USING entryset() :::::::::::: 
KEY : key1 - VALUE : Bangalore
KEY : key3 - VALUE : India
KEY : key5 - VALUE : New Delhi
KEY : key2 - VALUE : Mumbai
KEY : key4 - VALUE : Chennai