Wednesday, December 21, 2011

How to get width and height of an image in Java

Following method can be used to get width and height of jpg, gif, or png file
import javax.swing.ImageIcon;

public void printSize(){
  ImageIcon jpegImage = new
  ImageIcon("C:\\Users\\prageethj\\Desktop\\cute.jpg");
  int height = jpegImage.getIconHeight();
  int width = jpegImage.getIconWidth();
  System.out.println(width + "x" + height);
}

Database Access in Java (JDBC Example)

Accessing and retrieving data from a database is very simple.
First of all you need to add the DB driver(.jar) to your project. After that you can use below code.
In this example I am using mySql database.
//load DB driver
Class.forName("com.mysql.jdbc.Driver");
//this is the connection string
String connString 
   = "jdbc:mysql://localhost:3306/mydb?user=root&password=";  
//Create connection
Connection con = DriverManager.getConnection(connString);
//Create a Statement object using connection
Statement statement = con.createStatement();
//Execute the SQL statement and get the results as a Resultset(Note that the name of the table is 'employee')
ResultSet resultSet = statement.executeQuery("select * from 
           employee");
//Now we can iterate through the resultSet 
while(resultSet.next()){
//following method returns the value in Object type. 
//'name_full' is the column name
  Object o = resultSet.getObject("name_full");
  System.out.println(o);
//following method returns the value in String type.
 String s = resultSet.getString("name_full");
}
Note that you can remove above first two lines of the code and replace third line from below line to get the same result.
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydb", "root", "");

How to add and subtract years, months and days using Calendar class

In Java the best option for you is using the Calendar object.
Calendar c = Calendar.getInstance();//Create Calendar instance
Date today = c.getTime();//Initially this returns today
System.out.println(today);

c.add(Calendar.YEAR, 10);//Add 10 years
c.add(Calendar.MONTH , 1);//Add a month
c.add(Calendar.DATE, 5);//Add 5 days
Date futureDay = c.getTime();
System.out.println(futureDay);

Note that when you are using the Calendar class you need not to bother about number of days the month contains, leap years etc.
Similarly in order to subtract 10years just use -10 as below
c.add(Calendar.YEAR, -10);//Subtract 10 years