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

Friday, May 20, 2011

How to take a screenshot of your desktop

This tutorial shows you how to capture a screenshot of your desktop.
import java.io.File;
import javax.imageio.ImageIO;
import java.awt.Rectangle;
import java.awt.Robot;
import java.awt.image.BufferedImage;

try {
  Robot robot = new Robot();
  //I assume that the size of the image you want is 300 x 200
  BufferedImage img = robot.createScreenCapture(new                                                Rectangle(300,200));
  //I am saving the image as a png image
  //But you can use any other image formats like bmp, jpg etc.
  ImageIO.write(img, "png", new File("D:/screen.png"));
} catch (Exception ex) {
  ex.printStackTrace();
}

Ok. But sometimes you may want to capture the whole screen.
So you have to import Toolkit first.
import java.awt.Toolkit;

Your new code will look like this.
try {
  Robot robot = new Robot();
  Rectangle rect = new Rectangle( Toolkit.getDefaultToolkit().getScreenSize());
  BufferedImage img = robot.createScreenCapture(rect);
  ImageIO.write(img, "png", new File("D:/screen.png"));
} catch (Exception ex) {
  ex.printStackTrace();
}

Thursday, May 19, 2011

How to execute a DOS command using Java.

As you know "mkdir" is the DOS command which lets you create a new folder at a given location.
In order to create a folder named as "MyFolder" in your "C:" drive you can use the following command.
>>mkdir c:\MyFolder

But in java you need to do an additional work to execute this command.
So you have to add "cmd /c" to your command.
Following code creates a new folder named as "MyFolder" in drive "C:".
String cmd = "cmd /c";
String command = "mkdir";
String folderName = "C:\\MyFolder";
Runtime.getRuntime().exec(cmd + " " + command + " " + folderName);

But what will happen if your folder name contains space characters.
For an example if the name of your folder was "My Folder" instead of "MyFolder".
Then you should add extra double quotes and escape them as below.
String folderName = "C:\\\"MyFolder\"";

Wednesday, May 18, 2011

How to replace a character or a word at a given position in Java.

Lets assume that you want to replace the 7th character ("-") in following string with "*" character.
Then you can do it as below.
String s = "I*LIKE-JAVA BUT MY FRIEND LIKE .NET.";
System.out.println(s.substring(0,6) + "*" + s.substring(6 + 1));

Note that in above string there are two occurances of the word "LIKE".
If you want to replace the first occurances of the word "LIKE" with the word "LOVE" then you can do it as below.
String s = "I*LIKE-JAVA BUT MY FRIEND LIKE .NET.";
System.out.println(s.substring(0,2) + "LOVE" + s.substring(2 + 4));

Below example shows you how to remove a character at a certain position.
In this example we remove the "*" characterfrom the text.
String s = "WE*LIKE";
System.out.println(s.substring(0,2) + s.substring(3));

If you want to remove all the "*" from the string "I*LOVE*JAVA" then you can use below method.
String initialString = "I*LOVE*JAVA";
String result = "";
for (int i = 0; i < initialString.length(); i ++) {
 if (initialString.charAt(i) != '*') {
  result += initialString.charAt(i);
 }
}
System.out.println(result);

Read a file line by line

 In this example I explain how to read a file line by line and add the lines to a List.

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JOptionPane;

public static void main(String[] args) throws IOException {
  String fileName = "c:\\camera.log"; \\Path to your file
  FileReader reader = new FileReader(fileName);
  BufferedReader buffReader = new BufferedReader(reader);
  List linesList = new ArrayList();
  String line;
  while((line = buffReader.readLine()) != null){
    linesList.add(line);
  }
  //For this example I just show a message box to display the content of the file.
  JOptionPane.showMessageDialog(null, linesList.toArray());
}