Monday, May 31, 2010

Reading Text Files In a Java Program II :: Using a FileReader and a BufferedReader

0 comments
In this example we use a FileReader object wrapped by a BufferedReader object to read a plain text file. This method is more efficient than reading raw bytes and converting them into character array.

Constructors of BufferedReader class
BufferedReader(Reader in)
BufferedReader(Reader in, int inpBuffSize) : When we use this constructor we must specify the size of the input buffer.

Code:
//© http://imagocomputing.blogspot.com/ 
import java.io.FileReader;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.IOException;

public class ReadTxtFile{
 public static void main(String args[]){
  try{
   String fileContent="";
   //create a FileReader object(fin)
   FileReader fin=new FileReader("myFile2.txt");
   //wrap FileReader object(fin) using a BufferedReader 
   BufferedReader buffR=new BufferedReader(fin);
   String line;
   while((line=buffR.readLine())!=null){
    fileContent+=line+"\n";
   }
   System.out.println(fileContent);
   buffR.close();
   fin.close();
  }catch(FileNotFoundException e){
   System.err.println("File not found : " + e.getMessage());
  }catch(IOException e){
   System.err.println("Error in file stream! : " + e.getMessage());
  }
 }
}
Output :

Explanation:
Line 12 : We create a FileReader object to read out targeted text file
Line  14: Wrap the FileReader object (fin) by a BufferedReader(buffR) this allows us to read file content line by line.

Class FileReader Since : JDK1.1
Class BufferedReader Since : JDK1.1

Sunday, May 30, 2010

Reading Text Files In a Java Program :: Using a FileReader

2 comments
FileReader class is located in Java I/O package (java.io.FileReader). using this class we can read character files. In other words we can read character streams using FileRead class. If our purpose is reading bytes (raw bytes) from the files we can use FileInputStream.

Constructors of FileReader class.
FileReader(File file)   
FileReader(String fileName)
FileReader(FileDescriptor fd) : File reader provides three handles to standard I/O streams such as in,out,err (FileDescriptor.in, FileDescriptor.out, FileDescriptor.err)

Lets see an example to undestand the FileReader class.
//© http://imagocomputing.blogspot.com/ 
import java.io.FileReader;
import java.io.FileNotFoundException;
import java.io.IOException;

public class ReadTxtFile {
 public static void main(String args[]) {
  try{
   FileReader fin=new FileReader("myFile.txt");
   String fileContent="";
   char buff[]=new char[512];
   int len;
   while((len=fin.read(buff))!=-1){
    fileContent+=(new String(buff,0,len));
   }
   /*now fileContent variable contains
    *the whole text in the targeted file
    */
   System.out.println(fileContent);
   fin.close();
  }catch(FileNotFoundException e){
   System.err.println("File not found : " + e.getMessage());
  }catch(IOException e){
   System.err.println("Error in file stream! : " + e.getMessage());
  }
 }
}
Output :
Explanation :
In line 9 we create FileReader object called fin
Then we read file iteratively. First we read set of characters into char array then we append it to  fileContent variable.
After reading whole content we can do several manipulations with the file content in this example I have printed the file content to the standard output stream.

Class : FileReader
Since : JDK1.1

Wednesday, May 12, 2010

String Class in Java

0 comments
String objects contain sequence of charters. Strings can be concatenate using ( + ) operator which is a special java language feature. String class represent a string using UTF -16 (unicode character representation in java)   
There are different constructors available in Java we have to select the most suitable construct for our purpose. (Click here to see the constructor summary)
Following methods are available in the String class.
length()
charAt(int index)
compareTo(String str)
compareToIgnoreCase(String str)
concat(String str)
endsWith(String suffix)
equals(Object obj)
equalsIgnoreCase(String str)
indexOf(String str)
lastIndexOf(String str)
replace(char oldChar,char newChar)
split(String regex)
startsWith(String prefix)
substring(int beginIndex)
trim(String s)
Lets see some example written to demonstrate the above methods.
Compare the code with given output.
 
//© http://imagocomputing.blogspot.com/ 
class StringDemo {
 public static void main(String args[]){
  String str1="Sri Lanka is the most beautiful country";
  String str2="Java is a OOP language";
  System.out.println("Length of str1 : " + str1.length());
  System.out.println(str1.compareTo(str2));
  System.out.println(str1.endsWith("try"));
  System.out.println(str1.equals(str2));
  System.out.println(str1.equalsIgnoreCase(str2));
  System.out.println(str1.indexOf("Lanka"));
  System.out.println(str1.lastIndexOf("t"));
  String newStr=str2.replace("J","L");
  System.out.println("Replaced string : " + newStr);
  System.out.println(str1.startsWith("Sri"));
  String subStr=str1.substring(22);
  String beforeTrim="       Hello Sri Lanka        ";
  String afterTrim=beforeTrim.trim();
  System.out.println("Before trim : " + beforeTrim);
  System.out.println("Aftre trim  : " + afterTrim);
 }
}

Wednesday, May 5, 2010

Using StringTokenizer Class

0 comments
StringTokenizer  is shipped in java.util package. This can be used to split a string using a given delimiter. Space character is the default delimiter for any string.
There are three important methods in StringTokenizer class.
lets see some java code to understand these methods.


//© http://imagocomputing.blogspot.com/
import java.util.StringTokenizer;
class TokenizerDemo {
 public static void main(String args[]){
  String MyStr="Sajith#Nimal#Kamal#Sunil";
  StringTokenizer tokens=new StringTokenizer(MyStr,"#");
  System.out.println("Real String     : " + MyStr);
  System.out.println("Number of tokens: " + tokens.countTokens());
  int i=1;
  while(tokens.hasMoreTokens()){
   System.out.println("Token " + i +" \t: " + tokens.nextToken());
   i++;
  }
 }
}
output :


A Practical Example:
//© http://imagocomputing.blogspot.com/
import java.util.StringTokenizer;

class GetExtensionDemo {
 static String getFileExtension(String filePath){
  StringTokenizer stk=new StringTokenizer(filePath,".");
  String FileExt="";
  while(stk.hasMoreTokens()){
   FileExt=stk.nextToken();
  }
  return FileExt;
 }

 public static void main(String[] args){
  String path1="/usr/bin/myProg.pl";
  System.out.println("File path : " + path1 + " File extension : " + getFileExtension(path1));
  String path2="C:\\about.bmp";
  System.out.println("File path : " + path2 + " File extension : " + getFileExtension(path2));  
 }
}
Output :
Since : JDK1.0
 

Stats

ලාංකීය සිතුවිලි

lankeeya sithuwili

Blog Catalogs

 

Let's Learn Java API. Copyright 2010 All Rights Reserved