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