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");
}
//Close the Statement object and Connection object.
statement.close();
con.close();
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\"";

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());
}

Increase the size of an array

In Java there is no direct way to increase the size of an array after is is defined.
In this post I will show you how to do this easily.
Think you have following array. The size of this array is 1.

String[] arr = new String[1];

Now you can increase the size of your array like this.(replace the word "NEW_SIZE" with your new size)

arr=(String[]) Arrays.asList(arr).toArray(new String[NEW_SIZE]);

Wednesday, March 9, 2011

How to read a file line by line in Java

In this example I explain how to read a text 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"; \\This is the path to your
                                       file
   FileReader reader = new FileReader(fileName);
   BufferedReader buffReader = new BufferedReader(reader);
   List<string> linesList = new ArrayList<string>();
   String line;
   while((line = buffReader.readLine()) != null){
     linesList.add(line);
   }
   //For the purpose of this example I just show a message box to
    display the content of the file.
   JOptionPane.showMessageDialog(null, linesList.toArray());
}

How to center the form(JFrame) in the screen in java

This example shows how to center a form in your screen
 import java.awt.Dimension;
 import java.awt.Toolkit;
 import javax.swing.JFrame;


 public static void main(String[] args){
    JFrame myForm = new JFrame("Centered Form");
    myForm.setSize(250, 200);
    Toolkit toolkit = Toolkit.getDefaultToolkit();
    Dimension screenSize = toolkit.getScreenSize();
    //Following three lines make the form centered
    int x = (screenSize.width - myForm.getWidth())/2;
    int y = (screenSize.height - myForm.getHeight())/2;
    myForm.setLocation(x, y);
    myForm.setVisible(true);
}

Wednesday, March 2, 2011

How to open a file with associated program in Java

First you need following imports
  import java.awt.Desktop;
  import java.io.File;
  import java.io.IOException;

Now you can create a Desktop object and call the open() method.
  Desktop desktop = Desktop.getDesktop();
  File f = new File("C:\\readme.txt");
  try {
    desktop.open(f);
  } catch (IOException ex) {}

In java how to replace a character or a word at a given position.

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 occurrences 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);

Tuesday, March 1, 2011

Split a string at asterisk(*) character

In this case you have to escape the asterisk(*) character as below.
String s = "I*LOVE*JAVA";
String[] parts = s.split("\\*");
for (int i = 0; i < parts.length; i++) {
  System.out.println(parts[i]);
}

How to copy a file from one folder to another folder in Java

Assume that you want to copy the file "C:\\a.txt" to another location. Then you can use following method. 
You can easily change the name of the second file at the same time.
(Note that my first file is a.txt and the name of the new file is b.txt)

try {
  String path1 = "C:\\a.txt";
  String path2 = "D:\\b.txt";
  File file1 = new File(path1);
  File file2 = new File(path2);
  FileInputStream fis = new FileInputStream(file1);
  FileOutputStream fos = new FileOutputStream(file2);
  byte[] byteArray = new byte[1024];
  int i = 0;
  while((i = fis.read(byteArray) )!= -1) {
    fos.write(byteArray, 0, i);
  }
  fis.close();
  fos.close();
} catch (Exception e) {
  e.printStackTrace();
}

Move a file from one folder to another folder in Java

You can give another name for moved file as in this example.
(i.e: My original file name is "a.txt" and after moving its name is changed to "b.txt")
try {
  File fileBeforeRename = new File("c:\\a.txt");
  File fileAfterRename = new File("D:\\NewFolder\\b.txt");
  boolean result = fileBeforeRename.renameTo(fileAfterRename);
  System.out.println(result);
} catch (Exception e) {
  e.printStackTrace();
}

How to rename a file in Java

try {
    File fileBeforeRename = new File("c:\\a.txt");
    File fileAfterRename = new File("c:\\b.txt");
    boolean result = fileBeforeRename.renameTo(fileAfterRename);
    System.out.println(result);
} catch (Exception e) {
    e.printStackTrace();
}

String to Character array

In java it is very easy to convert a String in to char array
String str = "Go ahead.";
char[] cArray = str.toCharArray();
System.out.println("Size = " + cArray.length);
for (char c : cArray){
System.out.println(c);
}
Run this code and note that the character and the full-stop character are also included in the char array.

How to get the current directory path

If you want to get the path to the folder where the application is running use following code.
String currentdir = System.getProperty("user.dir");

Get the character at a certain position in a string in Java

Assume that you want to get the 2nd character of the text "My Text". Then you can get the second character as below.
String txt = "My Text";
System.out.println(txt.charAt(1));//Remember that the index is zero based.

If you want to get the last character as a char, use the following method.
String txt = "My Text";
char lastChar = txt.charAt(txt.length() - 1);
System.out.println(lastChar);


If you want to get the last character as a String, use the following method.
String last = txt.substring(txt.length()-1);
System.out.println(last);

Convert char array to a string in java (Simple example)

In Java it is very easy to convert a char array in to a string. In String class there is a constructor you can pass a char array. See following simple example.

  char [] cArray = { 'I',' ','L','o','v','e',' ','J','a','v','a' };
  String text = new String(cArray);
  System.out.println(text);

Monday, February 28, 2011

How to set the focus to a component in java

Assume that you have a text field in your jFrame form and you want the cursor to set to that field after a button click.
If the name of your textField is "textField1" then use the following code as the button action.

textField1.requestFocusInWindow();

How to get the path to the desktop

You can use the following code to get the full path to the current user's desktop folder.

String desktopPath = System.getProperty("user.home") + "/Desktop";
System.out.print(desktopPath.replace("\\", "/"));

How to open an external URL with default browse in Java


try {                                                             
  URI uri = new URI("http://www.google.lk"); //This line may throw
                                               URISyntaxException 
  Desktop desktop = Desktop.getDesktop();
  desktop.browse(uri); //This line may throw URISyntaxException
} catch (URISyntaxException e) {

} catch (IOException e) {

}


How to rename a file in Java

This simple example shows you how to rename a file in Java.
try {
    File oldFile = new File("C:\\a.txt");
    File newFile = new File(C:\\b.txt);
    boolean isSuccess = oldFile.renameTo(newFile);
    System.out.println(isSuccess);
} catch (Exception e) {
    e.printStackTrace();
}