Sunday, October 3, 2010

Determine user details from a Java program

7 comments
When we want to get details of the host pc from a java program , we can use the getProperty() method of System class in java.lang package. According to the java documentation(SE6) we can get following information using this class.
Key Description of Associated Value
java.version Java Runtime Environment version
java.vendor Java Runtime Environment vendor
java.vendor.url Java vendor URL
java.home Java installation directory
java.vm.specification.version Java Virtual Machine specification version
java.vm.specification.vendor Java Virtual Machine specification vendor
java.vm.specification.name Java Virtual Machine specification name
java.vm.version Java Virtual Machine implementation version
java.vm.vendor Java Virtual Machine implementation vendor
java.vm.name Java Virtual Machine implementation name
java.specification.version Java Runtime Environment specification version
java.specification.vendor Java Runtime Environment specification vendor
java.specification.name Java Runtime Environment specification name
java.class.version Java class format version number
java.class.path Java class path
java.library.path List of paths to search when loading libraries
java.io.tmpdir Default temp file path
java.compiler Name of JIT compiler to use
java.ext.dirs Path of extension directory or directories
os.name Operating system name
os.arch Operating system architecture
os.version Operating system version
file.separator File separator ("/" on UNIX)
path.separator Path separator (":" on UNIX)
line.separator Line separator ("\n" on UNIX)
user.name User's account name
user.home User's home directory
user.dir User's current working directory

I have written a Java class to encapsulate these data. lets see the class and a sample program.

class UserInfo
//© http://imagocomputing.blogspot.com/

class UserInfo {
 private String getInfo(String key){
  return System.getProperty(key);
 }
 
 public String getVersion(){
  return getInfo("java.version");
 } 
 
 public String getJavaHome(){
  return getInfo("java.home");
 } 
 
 public String getTempDir(){
  return getInfo("java.home");
 } 
 
 public String getOS(){
  return getInfo("os.name");
 } 
 
 public String getOSVer(){
  return getInfo("os.version");
 } 
 
 public String getUserName(){
  return getInfo("user.name");
 } 
 
 public String getUserHome(){
  return getInfo("user.home");
 } 
 
 public String getfileSeperator(){
  return getInfo("file.separator");
 }
}
class UserInfoTest
class UserInfoTest {
 public static void main(String args[]){
  UserInfo useInf=new UserInfo();
  System.out.println("JRE Version \t: "+useInf.getVersion());
  System.out.println("JRE Directory \t: "+useInf.getJavaHome());
  System.out.println("JRE Temp Dir \t: "+useInf.getTempDir());
  System.out.println("OS Name \t: "+useInf.getOS());
  System.out.println("OS version \t: "+useInf.getOSVer());
  System.out.println("User Name \t: "+useInf.getUserName());
  System.out.println("User Home \t: "+useInf.getOSVer());
  System.out.println("File Seperator \t: "+useInf.getfileSeperator());
 }
}

Output:

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
 

Monday, April 19, 2010

Getting Keyboard Inputs II

0 comments
In previous method for getting keyboard inputs we used buffered readers and input stream readers. There is a special class called Scanner available in java.util package which can be used to get keyboard inputs. Using a Scanner object we can read converted values directly into our program which means we haven't to convert read values explicitly. Scanner class be used to perform many other tasks. Lets see a simple Java program to understand its usage.

//© learnjavaapi.blogspot.com  
import java.util.Scanner;
class ScannerDemo{
 public static void main(String args[]){
  int num1;
  float num2,tot;
  String name;
  Scanner scn=new Scanner(System.in);
  System.out.print("Enter your name \t: " );
  name=scn.nextLine();
  System.out.print("Enter a Float value  \t: " );
  num2=scn.nextFloat();
  System.out.print("Enter an Integer value \t: " );
  num1=scn.nextInt();
  tot=num1+num2;
  System.out.println("Hi "+name+" total is \t: "+ tot );
 }
}

Output :

In above example I have used the created Scanner object to read three different data. String,int and float. See the java documentation for more details about Scanner class.
Class : Scanner
Since : Java 1.5
Scanner

Sunday, April 18, 2010

Getting Keyboard Inputs I

0 comments
In order to get inputs from the keyboard we can use standard input stream (System.in ) available in the java.lang package. Generally standard input stream contains byte stream coming from the keyboard. Of cause we can change the standard input. In this example I have used an  InputStreamReader object to read the input stream. Lets see a simple java program written to demonstrate how to get keyboard inputs in java.

//© learnjavaapi.blogspot.com  
import java.io.InputStreamReader;
import java.io.BufferedReader;
import java.io.IOException;
class GetInput{
 public static void main(String args[]) throws IOException{
  InputStreamReader in=new InputStreamReader(System.in);
  BufferedReader br=new BufferedReader(in);
  System.out.print("Please Enter your name : ");
  String name=br.readLine();
  System.out.println("Hi "+ name +" how are you ? ");
  in.close();
  br.close();
 }
}

Output :

Let me explain important parts of this program.
In the first three lines I have imported essential classes. By using throws keyword I have thrown IOException from my program. So all input/output exceptions are ignored in our program. By creating InputStreamReader object called in our program is ready to get keyboard inputs. For better input handling BufferedReader object br is used. This joining is called wrapping InputStreamReader object within BufferedReader object. InputStreamReader reads bytes from the input stream and decodes them into characters.
JavaDoc:

Stats

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

lankeeya sithuwili
There was an error in this gadget

Blog Catalogs

 

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