Monday, February 28, 2011

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

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