Showing posts with label java.io. Show all posts
Showing posts with label java.io. Show all posts

Thursday, February 19, 2009

java File

File:
A File Object is an abstract representstion of name of a file or directory.

File f=new File(“abc.txt”);
Ststem.out.println(f.exits()); ------------>output: false
F represents a file abc.txt only
File f=new File(“Laxman”);
F represents a diretory ‘Laxman’.
.java file object represents both files and diretory(unix terminology).

Constructors of the File class:
--> File f=new File (String name)
create a file instance that represents the name of the file or directory.
--> File f =new File(String diretory,string name)
creates a file instance that represents a diretory or file name in the specified directory.
---> File f=new File(File dir,String name)
create a new file instance that represents a file or diretory name in the specified directory.
If the specified is not exists we will find an exception saying IOException system can’t find the specified diretory.
Methods of the File class:
1.boolean exists()
return true if the file or diretory exists,otherwise false.
2.boolean createNewFile()
returns true if it will create a new file otherwise false.
3.boolean mkdir()
create the new diretory and returns true if the directory already present returns false.
4.boolean isFile()
return true if the file object represents File
5.boolean isDirectory()
Inorder to check whether the file object represents,physical file name or directory.
6.String[] list()
returns the files/directory name present in the directory.
7.boolean delete()
delete the file or directory represented by file object.
8.boolean renameTo(File destination)
1)Write a program(WAP) to create a file named with “xyz.txt” in the current directory.
2)WAP for createing a directory laxman123 in the current working directory and in that create a file named with file1.txt.
3.WAP a program to list all the files and directories present in directory laxman123.
File Example :
1. Class Sample
{
public static void main(String add[])
{
File f=new File(“xyz.txt”);
If (!f.exists())

f.createNewFile();

System.out.println(f.exists());
}
}
2. class Sample
{
public static void main(String aff[])
{
File f=new File(“laxman.txt”);
If(!f.exists())
f.mkdir();
File f1=new File(“laxman”,”laxman txt”);
F1.createNewFile();
System.out.println(f1.exists());
}
}
3. Class Samle
{
public static void main(String ah[])
{
File f=new File (“laxman123”); ------------->already exists
String[] s=f.list();
for(String s1:s)
{
System.out.println(s1);
}
}
With the same name there may be a chance of a file or a directory .From java code creating the file followed by creating the directory with the same name allowed and File object represents a file only.
After creating the directory ,if we are creating file with tha same name we will get RTE saying IOException:Access is denied
File f=new File(“dir1”,”file1.txt”);
This file object represents a file named with file1.txt which will present in the directory
f.writeNewFile();
If the directory is not present then f.createNewFile() results a RTE saying IOException:The system can not find the path specified.
If we call list() method on java file object which represents a physical file instead of directory.it just simply return null.
If applied on directory it returns the content of the directory.

java All Reader classes

FileReader class:
If is the child class of abstract class reader this can be used for reading charater data from a file.
FileReader Constructors:
1.FileReader fr=new FileReader(String fname)
2.FileReader fr=new FileReader (Filename f)
if the file is not found these constructors raise RTE saying FileNotFound Exception
Methods:
1. int read()throws IOException
return the Unicode of the next charater if it is exists else---1.
2.int read(char[] ch)
returns the number of charaters from the file and populated in the specified array.
3.void close()
the flushing is not reqired while reading data .so MISSING
File Reader Examples:
FileReader fr=new FileReader(“laxman.txt”);
System.out.println(“fr.read());
Char[] ch =new char[200];
Fr.read(ch);
For(char c1:ch)
System.out.println(c1);
Fr.close();

BufferedReader:
By using this we can improve the performance.It contain a separate method readLine() to read single line at a time instead of single charater.
So this is the more convenient class for reading charater data from a file
Constructors:
1.BufferedReader br=new BufferedReader(Reader r)
2.BufferedReader br=new BufferedReader(Reader r,int size)
Methods:
1.int read()throws IOException
to read a single character
2.int read(char[] ch)throws IOException
to read an array of character
3.String readLine()
to read nextline a single line.
If there is no next line return null
BufferedReader Example:
FileReader fr=new FileReader(“laxman.txt”);
BufferedReader br=new BufferedReader(fr);
String s=br.readLine();
While(s!=null)
{
System.out.println(s);
S=br.reaadLine();
}
br.close();
}


java All writer classes

FileWriter:
This is a child class of writer .this class can be used for writing charater data.
FileWriter constructors:
1.FileWriter fw=new FileWriter(Filename)
create a filewriter object to the given file if the file having this name ,doesn’t exists this constructor automatically creates the corresponding file also.But this is not possible in the case of File constructor.
2.FileWriter fw=new FileWriter(File f)
create FileWriter object for the specified File f .if the file is not already present this constructor wilol create automatically the file also.
3.FileWriter fw=new FileWriter(String file name,Boolean append)
If the second argument is true the data append to the existing content .If it is false ,then the old data is over ridden by new data.
4.FileWriter fw =new FileWriter (File f, boolean append) ------>By default flase.
Methods of FileWriter:
1.void write(int ch)throws IOException
the Corresponding character can be written to the file.
2.void write(String s)throws IOException
writes a String to the file
3.void write(char[] ch)throws IOException
writes a charater array data ti the file
4.void flush()
to guarented that the last character of the data should be written to the file
5.void close()
To the close file writer object
6.void write(int unicodevalue)throws IOException
File writer Example:
Import java.io.*;
Class Sample
{
public static void main(String aff[])
{
File f=new File(“file1.txt”);
System.out.println(f.exists());
FileWriter fw =new FileWriter(f);
System.out.println(f.exists());
Fw.write(100);
Fw.write(“laxman software”);
Char[] ch={‘L’,’a’,’x’,’m’,’a’,’n’};
Fw.write(ch);
Fw.close();
Fw.flush();
}
}

  • while inserting the data ,the programmer is responsible to insert separately the line separator(\n).
  • When we are reading the data ,we have to put inside the char array.
  • we should know the size of the array in advance otherwise it will be a probleam .
  • we have to read the data charater by charater which increase the number of IO operations and decreses the performance of the system.
To overcome this ,SUN people has introduced buffered reader and bufferwriter class
BufferedWriter:
we can create a bufferedwriter object over any writer object.
Construtors:
BufferedWriter bf=new BufferedWriter(Writer w);
BufferedWriter bw=new BufferedWriter(Writer w,int size);
Where size is the size of the buffer
Methods:
1.void write(int i)throws IOException
To write one charater
2.void write(String s)throws IOException
to write the given string
3.void write(char[] ch)throws IOException
4.void newLine()
to insert a new line character
5.void flush()
6.void close()
Q.when compare with java.io.BufferedWriter to java.io.FileWriter which capability exists as a method in only one of .
a.closing system
2b.flushing the stream
c.writng to the stream
d.marking the location in the stream
e.writing the line separator to the string (valid)
Buffered Writer Example:
Class Sample
{
public static void main(String args[])
{
FileWriter fw=new FileWriter(“laxman.txt”);
BufferedWriter bw=new BufferedWriter(fw);
Bw.write(100);
Bw.write(“laxman”);
Bw..newLine();
Bw.write(“scjp”);
Bw.newLinw();
Bw.write(“srnagar”);
Bw.flush();
Bw.close();
Fw.close();
}
}

When ever we are closing the BufferedWriter autpmaticaly the stream opened by fileWriter is also closed.


PrintWriter:
The most convenient class for writing any kind of text data .It has enhanced in 1.5 version.
Constructors:
1.PrintWriter p=new PrintWriter(String name)
2.PrintWriter p=new PrintWriter(File name)
3.PrintWriter p=new PrintWriter(Writer w)
Methods:
1.void write(int ch)------> to write character
2.void write(String s)-----> to write String
3.void write(char[] ch)-----to write character
4.void print(int i) -----directory add the int
5.void print(String s)
6.void print(char[] ch)
7.void print(boolean b)
8.void print(char ch)
9.void print(long l)
10.void println(int i) -----directory add the int
11.void println(String s)
12.void println(char[] ch)
13.void println(boolean b)
14.void println(char ch)
15.void println(long l)
PrintWriter Example:
Import java.io.*;
Class Sample
{
public static void main(String add[])throws IOException
{
PrintWriter pw=new PrintWriter(“laxman.txt”);
Pw.write(100);
Pw.print(100);
Pw.print(true);
Pw.print(“laxman”);
Pw.print(“scjp”);
Pw.print(“Hyderabad”);
Pw.flush();
Pw.close();
}
}

Sunday, February 15, 2009

Serialization

Java Serialization(serializable):
The process of saveing an object data to a file is called serialization.
writeObject(o)
The process of retrieving an object data from the file is called deserialization.
By using read object method of ObjectInputStream we can achieve deserialization.
ObjectInputStream ----->FileInputStream------>abc.txt
serialization Example:
class Dog implements Serializable
{
int i=10;
int j=20;
transient int k=30;
}
public class Myser1 {
public static void main(String arg[])throws Exception

{
Dog d1=new Dog();
FileOutputStream fos=new FileOutputStream("abc.txt");
ObjectOutputStream oos=new ObjectOutputStream(fos);
oos.writeObject(d1);

FileInputStream fis=new FileInputStream("laxman.txt");
ObjectInputStream ois=new ObjectInputStream(fis);
Dog d2=(Dog)ois.readObject();
System.out.println(d2.i+"......"+d2.j);
}
}

It is suggestable our java bean classes should implements serialization.
Ois.readObject() method returns an object in the java.lang.Object form .we should perform the type casting.

  • All the Objects doesn’t have the capability of saving to the file .Only serializable Objects having this capability.
  • An object is said to be serializable if and only if the corresponding class implements serializable interface(directly or indirectly).
  • The serializable interface doesn’t contain any method and it is an example of marker interface.
  • If an object is non-serializable then we are not allow to save this object to the file.vilation leads to RTE saying java.io.net.serializableException.
  • All the wrapper classes,collection classes and arrays of primitives already implemented serializable interface.Hence these are serializable objects.
  • If you don’t want to save ,the value of a particular instance variable while performing serialization ,then we have to declare those variable as transient.
  • If we are declearing a variable as the transient ,while saving an object to the file JVM ignores ,the value of this variable ,instead of saving original value ,JVM stores default value for the transient variables.Hence transient means ‘not to serializable”.
  • Static variables are not part of object state hence they never participated in the serialization process.A single copy of the static variable will exist and all the objects will share that copy.
  • Final variable also never participated in the serialization.there is no effect of declearing a final or a static variable as transient.
Object Graphs:
When ever we are saving an objects to the file all the objects which are reachable from that object by default saving to the file.This group of object is called ObjectGraph.
Example:
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;

class Dog1 implements Serializable
{
Cat c=new Cat();
}
class Cat implements Serializable
{
int i=10;
Rat r=new Rat();
}
class Rat implements Serializable
{
int j=20;
}

class SerDemo2
{
public static void main(String arg[])throws Exception
{
Dog1 d=new Dog1();
FileOutputStream fos=new FileOutputStream("abc1.txt");
ObjectOutputStream oos=new ObjectOutputStream(fos);
oos.writeObject(d);
FileInputStream fis=new FileInputStream("abc1.txt");
ObjectInputStream ois=new ObjectInputStream(fis);
Dog1 d1=(Dog1)ois.readObject();
System.out.println(d1.c.i);
System.out.println(d1. c.r.j);
}
}

When ever we are saving an object to the file.All the object present in its objects graph by default will save to the file .Hence all the objects present in the object graph also must be serializable .voilation leads to RTE saying NotSerializable Exception”.
Example:
class Dog implements serializable
{
Cat c=new Cat();
}
Class Cat
{
Int j=20;
}
Class SerialDemo
{
public static void main(String arg[])
{
Dog d=new Dog();
FileOutputStream fos=new FileOutputStream(“abc.txt”);
ObjectOutputStream oos=new ObjectOutputStream(fos);
Oos.writeObject(d);
FileInputStream fis=new FileInputStream(“abc.txt’);
ObjectInputStream ois=new ObjectInputStream(fis);
Dog d1=(Dog)ois.readObject();
System.out.println(d1.c.j);
System.out.println(d1. c.j);
}
}
Customized Serialization:
During default serialization there may be a chance of loss of information .To over come these problems ,we can perform customized serialization .
We can perform customized serialization by using the following two call back methods.
1.private void writeObject(OutputStream os)
JVM calls this writeObject method at the time of serialization.
2.private void readObject(inputStream is)
the JVM calls this method at the time of deserialization automatically.
The above two methods are called by JVM automatically at the time of serialization and deserialization .Hence these methods are considered as call back methods.
Customized Serialization Example:
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;



class Dog2 implements Serializable
{
transient Cat1 c=new Cat1();
private void writeObject(ObjectOutputStream os)throws Exception
{
os.defaultWriteObject();
int i=c.j;
os.writeInt(i);
}
private void readObject(ObjectInputStream is)throws Exception
{
is.defaultReadObject();
int i=is.readInt();
c=new Cat1();
c.j=i;
}
}
class Cat1
{
int j=20;
}
public class SerDemo3
{
public static void main(String arg[])throws Exception
{
Dog2 d=new Dog2();
FileOutputStream fos=new FileOutputStream("abc.txt");
ObjectOutputStream oos=new ObjectOutputStream(fos);
oos.writeObject(d);
FileInputStream fis=new FileInputStream("abc.txt");
ObjectInputStream ois=new ObjectInputStream(fis);
Dog2 d1=(Dog2)ois.readObject();
System.out.println(d1.c.j);
}
}

Friday, February 6, 2009

java IO Package

examples java.io