Showing posts with label Java. Show all posts
Showing posts with label Java. Show all posts

Sunday, February 5, 2012

File handeling in java

Basic of file handeling
File handling capability made java a strong and robust programming language. One of the most frequently used task in programming is writing to and reading from a file. This function can achieve in java by include java’s io package. Classes related to input and output are present in the JavaTM language package java.io . Java technology uses "streams" as a general mechanism of handling data. Input streams act as a source of data. Output streams act as a destination of data. The file handeling capability can achive in java by two types
1)Byte Stream
2)Character Stream.
 You are probably aware that Java is one of the most popular programming languages that people use. It is so popular because it can be used so widely from application software to web applications and capable to read data from various device and application such as from Network socket,another file, other embaded device and also in XML  format.
To write anything to a file first of all we need a file name we want to use. The file name is a simple string like like this:
  •  String fileName = "myfile.txt";
If you want to write in a file which is located elsewhere you need to define the
complete file name and path in your fileName variable:
  •  String fileName = "c:\\path\\test.txt";
However if you define a path in your file name then you have to take care the path separator. On windows system the '\' is used and you need to backslash it so you need to write '\\', in Unix,Linux systems
the separator is a simple slash '/'.

Opening a file
To open a file for writing use the FileWriter class and create an instance from it.
The file name is passed in the constructor like this.New operator is used for allocating memory to object.
  •  FileWriter writer = new FileWriter(fileName);
This code opens the file in overwrite mode if file already exhists. If you want to append to the file then
you need to use an other constructor like this:   
  • FileWriter writer = new FileWriter(fileName,true);
Besides this the constructor can throw an IOException so we put all of the code inside
a try-catch block.
The syntax is simple
Try{
FileWriter writer = new FileWriter(fileName,true);
}
Catch(Exception ex)
{
 System.out.println(“Exception accur”);
}
Write to a text file
  public void writeFile() {
      String fileName = "c:\\test.txt";
   
      try {
          FileWriter writer = new FileWriter(fileName,true);
          writer.write("Test text.");
          writer.close();
      } catch (IOException e) {
          e.printStackTrace();
      }
  }
This program showing simple file write operation.
Reading the file content
File reading operation can achive by two types 1)Data input stream 2)File input stream


 File reading using data input stream
import java.io.*;

class FileRead {
  public static void main(String args[]) {
    try {
      FileInputStream fstream = new FileInputStream("C:/myfile.txt");
      DataInputStream in = new DataInputStream(fstream);
      BufferedReader br = new BufferedReader(new InputStreamReader(in));
      String str;
      while ((str = br.readLine()) != null) {
        System.out.println(str);
      }
      in.close();
    } catch (Exception e) {
      System.err.println(e);
    }
  }
}
This program  use DataInputStream for reading text file line by line with a BufferedReader. 
DataInputStream-This class read binary primitive data types in a machine-independent way. 
BufferedReader-This class read the text from a file line by line with it's readLine() method.

File reading using file input stream.
import java.io.*;

public class FileRead {
  public static void main(String[] args) {
    File file = new File("C:/file.txt");
    int ch;
    StringBuffer strContent = new StringBuffer("");
    FileInputStream fin = null;
    try {
      fin = new FileInputStream(file);
      while ((ch = fin.read()) != -1)
        strContent.append((char) ch);
      fin.close();
    } catch (Exception e) {
      System.out.println(e);
    }
    System.out.println(strContent.toString());
  }
}


FileInputStream- This class reads bytes from the given file name.
read()-The read() method of FileInputStream class reads a byte or array of bytes from the file. It returns -1 when the end-of-file has been reached.
StringBuffer- This class is used to store character strings that will be changed.
append()-The append() of StringBuffer class appends or adds the string representation of the char argument to this sequence.
Copy one file into another file
import java.io.*;    //Package import

public class CopyFile {
  private static void copyfile() {
    try {
      File f1 = new File("C:/file.txt");     //Source file
      File f2 = new File("C:/new.txt");      //Destination file  
      InputStream in = new FileInputStream(f1);
      OutputStream out = new FileOutputStream(f2, true);
      byte[] buf = new byte[1024];
      int len;
      while ((len = in.read(buf)) > 0) {
        out.write(buf, 0, len);
      }
      in.close();
      out.close();
      System.out.println("File copied.");
    } catch (Exception ex) {
      System.out.println(ex);
    }
  }

  public static void main(String[] args) {
    copyfile();
  }
}


Program to count words of a file
import java.io.*;

import java.util.*;



public class FileCountwords {

        public static void main(String[] args) throws Exception {

BufferedReader br = new BufferedReader(new FileReader("C:/file.txt"));

                String line = "", str = "";

                int count = 0;

                while ((line = br.readLine()) != null) {

                        str += line + " ";

                }

                StringTokenizer st = new StringTokenizer(str);

                while (st.hasMoreTokens()) {

                        String s = st.nextToken();

                        count++;

                }

                System.out.println("File has " + count + " words.");

        }



}
It will print the number of words into a file.




Friday, February 3, 2012

Introduction to package in java

What is package?

Packages are a beautiful concept in java. It gives facility to user to create there won class Just like java’s pre defined class. User can create and include there won class using simple import statement. It’s gives us the same concept of “class library” in other programming language.In fact it is container of classes. It’s  possible to include both class and interface within package.
Package are containers for classes that are used to keep the class name space compartmentalized. For example,a package allows you to create a class named xyz (any name given by you),which you can store in your own package with out any concern that it will collide with other packages. Package is, a collection of .class files,created by the user or predefined.

Diagram of java package.


Some benefit of Package
1)The classes contained in the packages of other program can easily reused.
2)Packages gives the idea of hiding class. So that other program cannot able to access it.
3)It helps to use existing code again and again. More than one program can access same package in same                time.
4)If two classname is same then simply put two class in two different package. It will protect name collision.

Java API provides a large number of classes grouped them into several packages depending on there functionality.say for example
Java.lang;
Java.util;
Java.io;
Java.net;

How to create Package
It is very simple, simply include package command as the first statement in a Java source file.Any classes declared in that file will belong to the specified package.
  
Package statement defines a name space in which classes are stored. If you omit the package statement, the class names are put into the default package,which has no name space.
Syntax:
          package pkg;
          Here 'pkg ' is the package name.
example:
      package Mypack;
      Mypack is package name.

1.Program to create a package   
                              //Pack.java, this class will be included in Mypack1
                              package Mypack1;
                              Public class Pack
                              {
                                    public int var=90;
                                    public char c='e';
                               public void show()
                                 {
                                  System.out.println("These R "+var);
                                  }
                               }

 Save the program in the directory with same name as that of package name.
 i.e, Save Mypack1 package in the Mypack1 directory( folder). and save it with class name given,Pack .class

2.Now complie the program:
   But don’t run, as there is no main(), the program will not run. Now after compiling .class file will be created, make sure that it will be in same directory(folder) where package is saved.

3.Accessing a package
We have to use import statement to include the package.Note that the statement end with semicolon .The import statement will come before class definition of source code file.
The syntax is
import packagename;
Or
import packagename.classname ;
If you want to import all class of particular package then put simply * after packagename
import packagename.*;

Example program of package.

Package package1;
Public class classname
{
    public void display()
 {
   System.out.println(“I am display function”);
 } 
}

Now compile and save it with classname.java and store into package1 folder.Make sure the package1 directory is the subdirectory of source code directory.

Now write the following program

import package1.*;
class test
{
  public static void main(String args[])
 {
     classname cl=new classname();
     cl.display(); 
 }
}

And the output will be “I am display function”;


Hiding a class into package

Package p1;
public class a
{
   //Body of a class
}
class b
{
  //Body of class b.
}

The class b is declared privately. So in main source code it is not possible to create object of b class.
Adding more class in package.
1)Define the class and make it public
2)Write package statement with same package name that you have already created.
Package mypack
public class newclass
{
}
3)Compile with newclass.java filename and save the class file in mypack directory.
4)Write the following statement to import both packages.
Import mypack.*;

Introduction of Threading in java

What is Threading Java support multithreading, that mean it is possible to run more than one task in a single java program. For example one subprogram can display a animation when one subprogram will built another one.A thread is similar to program that has single flow of control. In face our well-known main program is nothing but a single threaded program.
https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEh89fuYAvUSEi4GJuKxSLzeZGeJEU5MsGO9WXnNI0GzWFghQIHzl2lzi8WiH6FWW3G8S5-tcps61JKfg2AGfrRHAUGhvudcolot76gsdSxYw33RYtavMiFrLR7eZeOj1xmFee0pwfWfNYs/s320/java_threads.png





It is very similar with some people are working in a company and sharing the same resource. In nutshell  java do not exhicute threads simultaneously. But it exhicute one by one ,and the swichover process among threads is soo speedy it seem that they are exhicuting simultaneously. Threads in java are subprogram of main program and occupy same space.

Creation of thread.
In the most general sense, you create a thread by instantiating an object of type Thread.
Java defines two ways in which this can be accomplished:
• You can implement the Runnable interface.
• You can extend the Thread class, itself.




Implementing Runnable
The easiest way to create a thread is to create a class that implements the Runnable
interface. Runnable abstracts a unit of executable code. You can construct a thread on
any object that implements Runnable. To implement Runnable, a class need only
implement a single method called run( ), which is declared like this:
public void run( )
Inside run( ), you will define the code that constitutes the new thread. It is important to
understand that run( ) can call other methods, use other classes, and declare variables,
just like the main thread can. The only difference is that run( ) establishes the entry point
for another, concurrent thread of execution within your program. This thread will end
when run( ) returns.
After you create a class that implements Runnable, you will instantiate an object of type
Thread from within that class. Thread defines several constructors. The one that we will
use is shown here:
Thread(Runnable threadOb, String threadName)
In this constructor, threadOb is an instance of a class that implements the Runnable
interface. This defines where execution of the thread will begin. The name of the new
thread is specified by threadName.
After the new thread is created, it will not start running until you call its start( ) method,
which is declared within Thread. In essence, start( ) executes a call to run( ). The start(
) method is shown here:
void start( )
Here is an example that creates a new thread and starts it running:

// Create a second thread.

class NewThread implements Runnable {
Thread t;
NewThread() {
// Create a new, second thread
t = new Thread(this, "Demo Thread");
System.out.println("Child thread: " + t);
t.start(); // Start the thread
}
// This is the entry point for the second thread.
public void run() {
try {
for(int i = 5; i > 0; i—) {
System.out.println("Child Thread: " + i);
Thread.sleep(500);
}
} catch (InterruptedException e) {
System.out.println("Child interrupted.");
}
System.out.println("Exiting child thread.");
}
}
class ThreadDemo {
public static void main(String args[]) {
new NewThread(); // create a new thread
try {
for(int i = 5; i > 0; i—) {

System.out.println("Main Thread: " + i);
Thread.sleep(1000);
}
} catch (InterruptedException e) {
System.out.println("Main thread interrupted.");
}
System.out.println("Main thread exiting.");
}
}
Inside NewThread's constructor, a new Thread object is created by the following
statement:
t = new Thread(this, "Demo Thread");
Passing this as the first argument indicates that you want the new thread to call the run(
) method on this object. Next, start( ) is called, which starts the thread of execution
beginning at the run( ) method. This causes the child thread's for loop to begin. After
calling start( ), NewThread's constructor returns to main( ). When the main thread
resumes, it enters its for loop. Both threads continue running, sharing the CPU, until their
loops finish. The output produced by this program is as follows:
Child thread: Thread[Demo Thread,5,main]
Main Thread: 5
Child Thread: 5
Child Thread: 4
Main Thread: 4
Child Thread: 3
Child Thread: 2
Main Thread: 3
Child Thread: 1
Exiting child thread.
Main Thread: 2
Main Thread: 1
Main thread exiting.
As mentioned earlier, in a multithreaded program, the main thread must be the last
thread to finish running. If the main thread finishes before a child thread has completed,
then the Java run-time system may "hang." The preceding program ensures that the
main thread finishes last, because the main thread sleeps for 1,000 milliseconds between
iterations, but the child thread sleeps for only 500 milliseconds. This causes the child
thread to terminate earlier than the main thread. Shortly, you will see a better way to
ensure that the main thread finishes last.

Extending Thread
The second way to create a thread is to create a new class that extends Thread, and
then to create an instance of that class. The extending class must override the run( )
method, which is the entry point for the new thread. It must also call start( ) to begin
execution of the new thread. Here is the preceding program rewritten to extend Thread:
// Create a second thread by extending Thread
class NewThread extends Thread {
NewThread() {
// Create a new, second thread
super("Demo Thread");
System.out.println("Child thread: " + this);
start(); // Start the thread
}

// This is the entry point for the second thread.
public void run() {
try {
for(int i = 5; i > 0; i—) {
System.out.println("Child Thread: " + i);
Thread.sleep(500);
}
} catch (InterruptedException e) {
System.out.println("Child interrupted.");
}
System.out.println("Exiting child thread.");
}
}
class ExtendThread {
public static void main(String args[]) {
new NewThread(); // create a new thread
try {
for(int i = 5; i > 0; i—) {
System.out.println("Main Thread: " + i);
Thread.sleep(1000);
}
} catch (InterruptedException e) {
System.out.println("Main thread interrupted.");
}
System.out.println("Main thread exiting.");
}
}
This program generates the same output as the preceding version.