java input output


IOSTREAMS
 Stream:--Collection of bits and bytes moving from source to destination and destination to source
These STREAMS are mainly categorized into BYTESTREAM and CHARACTERSTREAMs.
to represent these we have  Pre-defined input and output stream classes in java.io package.
Every java program is connected with mainly 3 stream
ü  System.in-----standard input stream(keyboard)
ü  System.out-----standard output stream(console)
ü  System.err-----standard error stream(console)
 There are different subclasses for InputStream and OutputStream classes.
The FileInputStream and FileOutputSream help reading and writing data from files.  BufferedInputStream and BufferedOutputStream which acts as a cache to perform read/write operations. DataInputStream and DataOutputStream perform read/write operations by taking one byte at a time in primitive data types format.
 The reader and writer classes are used to read/write characters instead of bytes.
Files in Java
File is a collection of records or data. Which can be accessed into a java program by using File class in java.io package.
          File  f1= new File(“temp.txt”);
This is the sytax to declare a file.
Methods of File class 
1.getName() 2.getPath() 3.exists() 4.isFile()/isDirectory()
5.canRead()/canWrite() 6.lastModified() 7.length() 8.delete() 9.renameTo() 10.list() 11.mkdir().
Ex:
import java.io.*;
class Filemethod1{
public static void main(String [] args){
File f1 = new File("c:\\java","abc.txt");
System.out.println("Filename: " + f1.getName());
System.out.println("Filename: " + f1.getPath());
System.out.println("Filename: " + f1.getAbsolutePath());
System.out.println(f1.exists() ? "file exists" : "file not exists");
System.out.println(f1.isDirectory() ? "file is a directory" : "file is  not" + "a directory");
System.out.println(f1.isFile() ? "file is an ordinary file" :"file may be a named pipe");
} }
File Streams
File stream consists of FileInputStream and FileOutputStream.
FileOutputStream: Helps to create a FILE and write data to a file.
FileInputStream: Helps in reading data  from the actual disk files.
import java.io.*;
class IOEx {
      public static void main(String[] args) throws IOException{
                  File f=new File("d:/abc.txt");
                  FileOutputStream  fos=new FileOutputStream(f);
                  fos.write(1);
                 FileInputStream fis=new FileInputStream(f);
                  int x=fis.read();
                  System.out.println("from file"+x);                        
      }
}
//DataInputStream class example
import java.io.*;
class Dis {
   public static void main(String [] args) throws IOException    {
 DataInputStream dis = new DataInputStream(System.in);
System.out.println("enter name");
String name = dis.readLine();
System.out.println("Hello mr " + name);
} }
Ex:
import java.io.*;
public class DataIOStreamDemo {
public static void main(String[] args) {
      try{
      DataOutputStream dos=new DataOutputStream(new FileOutputStream("data.txt"));
      dos.writeChar('A');
      dos.writeBoolean(false);
      dos.writeInt(10);
            dos.writeUTF("hello");//unicode text format
            dos.writeDouble(12.5);
            dos.close();
      FileInputStream fis=new FileInputStream("data.txt");
           DataInputStream dis =new DataInputStream(fis);
         System.out.println("char:" + dis.readChar());
         System.out.println("char:" + dis.readBoolean());
         System.out.println("char:" + dis.readInt());
         System.out.println("char:" + dis.readUTF());
         System.out.println("char:" + dis.readDouble());
           dis.close();
      }catch (Exception e){
                  System.out.println("error:" +e);
      }
}  }
Buffered Reader
    Buffered Reader class is used to read the data in the form of char by char.
//BufferedReader class example
Ex:--
import java.io.*;
public class BreaderIsDemo {
public static void main(String[] args) throws IOException{
String str;
   BufferedReader br = new BufferedReader(new InputStreamReader(System.in));            System.out.println("enter 'exit' to terminate");
      do {
      str=br.readLine();//input
      System.out.println(str);
      }while(!str.equalsIgnoreCase("exit"));
   }  }
Serialization & DeSerialization
Serialization  is a process of converting JAVA objects into NETWORK supported form by storing the OBJECTS into a Serialisable file.
Deserialisation means converting NETWORK supported form to JAVA OBJECTS.
To support the Serialisation process our class must be implemented from java.io.Serializable.
Serialisable is a marker interface(which does’t have any methods) which gives only  identity to its implemented class that, this class is ready for serialization .
if we don’t want to serialize any data we can declare it as “transient”.
Ex:--
import java.io.*;
class Emp implements Serializable{
      int eid;    String ename;
      transient int age;
      Emp(int id,String name,int a){
                  eid=id;
                  ename=name;
                  age=a;
      }
}
class SerializationDeSerialization{
      public static void main(String[] args) throws IOException,Exception{
                  Emp   e1=new   Emp (100,"admin",23);
                  System.out.println(e1.eid +"\t"+e1.ename+"\t"+e1.age);
                  FileOutputStream  fos=new   FileOutputStream("object.ser");
                  ObjectOutputStream  oos=new  ObjectOutputStream(fos);
                  oos.writeObject(e1);
                  System.out.println("object serialized successfully .....");
                  FileInputStream  fis=new       FileInputStream("object.ser");
                  ObjectInputStream  ois=new ObjectInputStream(fis);
                  Emp e=(Emp)ois.readObject();
                  System.out.println("object de-serialized successfully .....");
                  System.out.println(e.eid +"\t"+e.ename+"\t"+e.age);
      }
}                                  
Output:-
100     admin   23
object serialized successfully .....
object de-serialized successfully .....
100     admin   0

No comments:

Post a Comment