Tuesday, May 20, 2014

Input and Output Streams

 

අද මං කියල දෙන්න යන්නේ ජව වල තියන තවත් concept එකක් වෙන Input and Output Streams ගැන.මේවා යොදාගන්නේ ප්‍රදාන වශයෙන්ම යම් තොරුතුරු මුලාශරයක් සමග සන්නීවේදනය කරන්න.මේ දත්ත මුලාශ්‍රය file ,computer memory හෝ අන්තර්ජාලය වෙන්න පලුවන්.
Input Streams :-දත්ත මුලාශ්‍රයකින් දත්ත කියවීම.
Output Streams :- දත්ත මුලශ්‍රයකට දත ලිවීම.

ජාවා වල ප්‍රදාන වශයෙන් ස්ට්‍රීම්ස් දෙකක් තියනවා 

1)Byte Streams :-  මේවා use කරන්නේ Bytes වල Input හා Output  Handel කරන්න. 
2)   Charactor Streams :- මේවා use කරන්නේ Charactors වල Input හා Output  Handel කරන්න.
Byte Stream Classes

මුලින්ම කියන්න ඕනේ මේවට අවශ ගොඩක් class ජව වල කලින් define කරලා තියනවා.අපිට අපි එක use කරලා ඒවා බලාගන්න පලුවන්.මේවා inherit වෙන මූලිකම class දෙක තමයි InputStream
හා OutputStream කියන්නේ.

 

Character Stream Classes
අපි යොදාගන්න ගොඩක් character stream class තියන්නේ ජාවා වල IO කියන paccage එකේ .එකට ගියෝත්හ් API එකේ ඔයාලට පහසුවෙන් බලාගන්න පලුවන් ඒ class මොනවද කියල.



 Package 
Class 
Use 
Tree 
Help 
Java™ Platform
Standard Ed. 6
FRAMES    NO FRAMES    





Package java.io
Provides for system input and output through data streams, serialization and the file system.
See:
          
Description
 
Class Summary
A BufferedInputStream adds functionality to another input stream-namely, the ability to buffer the input and to support the mark and reset methods.
The class implements a buffered output stream.
Reads text from a character-input stream, buffering characters so as to provide for the efficient reading of characters, arrays, and lines.
Writes text to a character-output stream, buffering characters so as to provide for the efficient writing of single characters, arrays, and strings.
A ByteArrayInputStream contains an internal buffer that contains bytes that may be read from the stream.
This class implements an output stream in which the data is written into a byte array.
This class implements a character buffer that can be used as a character-input stream.
This class implements a character buffer that can be used as an Writer.
Methods to access the character-based console device, if any, associated with the current Java virtual machine.
A data input stream lets an application read primitive Java data types from an underlying input stream in a machine-independent way.
A data output stream lets an application write primitive Java data types to an output stream in a portable way.
An abstract representation of file and directory pathnames.
Instances of the file descriptor class serve as an opaque handle to the underlying machine-specific structure representing an open file, an open socket, or another source or sink of bytes.
A FileInputStream obtains input bytes from a file in a file system.
A file output stream is an output stream for writing data to a File or to a FileDescriptor.
This class represents access to a file or directory.
Convenience class for reading character files.
Convenience class for writing character files.
A FilterInputStream contains some other input stream, which it uses as its basic source of data, possibly transforming the data along the way or providing additional functionality.
This class is the superclass of all classes that filter output streams.
Abstract class for reading filtered character streams.
Abstract class for writing filtered character streams.
This abstract class is the superclass of all classes representing an input stream of bytes.
An InputStreamReader is a bridge from byte streams to character streams: It reads bytes and decodes them into characters using a specified charset.
Deprecated. This class incorrectly assumes that bytes adequately represent characters.
A buffered character-input stream that keeps track of line numbers.
An ObjectInputStream deserializes primitive data and objects previously written using an ObjectOutputStream.
Provide access to the persistent fields read from the input stream.
An ObjectOutputStream writes primitive data types and graphs of Java objects to an OutputStream.
Provide programmatic access to the persistent fields to be written to ObjectOutput.
Serialization's descriptor for classes.
A description of a Serializable field from a Serializable class.
This abstract class is the superclass of all classes representing an output stream of bytes.
An OutputStreamWriter is a bridge from character streams to byte streams: Characters written to it are encoded into bytes using a specified charset.
A piped input stream should be connected to a piped output stream; the piped input stream then provides whatever data bytes are written to the piped output stream.
A piped output stream can be connected to a piped input stream to create a communications pipe.
Piped character-input streams.
Piped character-output streams.
A PrintStream adds functionality to another output stream, namely the ability to print representations of various data values conveniently.
Prints formatted representations of objects to a text-output stream.
A PushbackInputStream adds functionality to another input stream, namely the ability to "push back" or "unread" one byte.
A character-stream reader that allows characters to be pushed back into the stream.
Instances of this class support both reading and writing to a random access file.
Abstract class for reading character streams.
A SequenceInputStream represents the logical concatenation of other input streams.
This class is for Serializable permissions.
The StreamTokenizer class takes an input stream and parses it into "tokens", allowing the tokens to be read one at a time.
Deprecated. This class does not properly convert characters into bytes.
A character stream whose source is a string.
A character stream that collects its output in a string buffer, which can then be used to construct a string.
Abstract class for writing to character streams.
 
Exception Summary
Base class for character conversion exceptions.
Signals that an end of file or end of stream has been reached unexpectedly during input.
Signals that an attempt to open the file denoted by a specified pathname has failed.
Signals that an I/O operation has been interrupted.
Thrown when the Serialization runtime detects one of the following problems with a Class.
Indicates that one or more deserialized objects failed validation tests.
Signals that an I/O exception of some sort has occurred.
Thrown when serialization or deserialization is not active.
Thrown when an instance is required to have a Serializable interface.
Superclass of all exceptions specific to Object Stream classes.
Exception indicating the failure of an object read operation due to unread primitive data, or the end of data belonging to a serialized object in the stream.
Thrown when control information that was read from an object stream violates internal consistency checks.
Signals that a sync operation has failed.
The Character Encoding is not supported.
Signals that a malformed string in modified UTF-8 format has been read in a data input stream or by any class that implements the data input interface.
Signals that one of the ObjectStreamExceptions was thrown during a write operation.

අපි මේ ඔක්කොම class මතක තියාගන්න ඕනේ නෑ.අවශ වෙලාවට API එක use කරලා ඒවා පාවිචි කරන්නේ කොහොමද කියල විතරයි දැනගන්න ඕනේ.දැන් අපි බලමු මේවා use කරන විදිය.

Console Input
මුලික වශයෙන්ම System කියන එකට free define stream veriable තුනක් තියනවා.in ,out,err යන ඒවා.අපි පොඩ්ඩක් පහත programme එක පොඩ්ඩක් බලමු.
import java.util.Scanner;


public class Demo {

      /**
       * @param args
       */
      public static void main(String[] args) {
            // TODO Auto-generated method stub
            Scanner sc=new Scanner(System.in);//Create Scanner object
            String fileName;
            sc.next();
            sc.nextLine();
            sc.nextInt();

      }

}

මේකෙදි කරන්නේ Scannner object එකක් හදල එකේ තියන කිලින් define කරපු method පාවිචි කරලා විවිද consol input ගන්න එක තමයි.අපිට API එකින් පලුවන් මේකට අදාල ඔක්කොම method බලාගන්න. http://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html මේ තියන්නේ Scanner class එකේ online API ලින්ක් එක.
Console Output
Console Output එක ගන්න අපි සාමාන්යෙන් use කරන්නේ print() සහ println() කියන method දෙක තමයි.නමුත් Console Output ගන්න recommended  method  එක තමයි PrintWriter stream එක use කරන එක. අපි දැන් බලමු PrintWriter stream එක use කරන විදිය ...
import java.io.PrintWriter;


public class Demo {

      /**
       * @param args
       */
      public static void main(String[] args) {
            // TODO Auto-generated method stub
            PrintWriter pw = new PrintWriter(System.out, true);
            pw.println("This is a string");
            int i = -7;
            pw.println(i);
            double d = 4.5e-7;
            pw.println(d);
      }

}

අපි තව programme එකක් බලමු.

import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.Date;


public class Demo {

      /**
       * @param args
       */
      public static void main(String[] args) {
            PrintWriter pwFile = null;
            int i=0;
        Date date = new Date();
        try{
            pwFile = new PrintWriter("FileName");
            i++;
            pwFile.println(date);
            pwFile.write("Write something in a line. i = "+i);
            System.out.println("Write to the file successfully");
        }catch(FileNotFoundException e) {
            e.printStackTrace();
        }catch(SecurityException e) {
            e.printStackTrace();
        }finally {
                 if(pwFile != null){
                pwFile.close();
            }
        }
        
          }
      }

මේ programme එකේ කරන්නේ printWriter එකට දෙන Destination file එකට දවස print කරන එක තමයි.

Object Serialization
ජාවා වලින් සපයන Object Serialization කියන technique එක use කරලා byte sequence එකක් විදියට object එකක තියන data ,information වගේ දේවල් නීරුපනය කරන එක තමයි.
Serialization සාමාන්යෙන් use කරන්නේ graphs ,  trees වගේ සංකීර්ණ data structures වල තමයි.
අපි දැන් මේකට පොඩි උදාහරණ ටිකක් බලමු.
import java.io.FileOutputStream;
import java.io.ObjectOutputStream;


public class Demo {

      /**
       * @param args
       */
      public static void main(String[] args) {
            // TODO Auto-generated method stub
            try {
                        MyClass object1 = new MyClass("Hello", -7);
                        System.out.println("object1: " + object1);
                        FileOutputStream fos = new FileOutputStream("serial");
                        ObjectOutputStream oos = new ObjectOutputStream(fos);
                        oos.writeObject(object1);
                        oos.flush();
                        oos.close();
                  }
                  catch(Exception e) {
                        System.out.println("Exception during serialization: " + e);
                        System.exit(0);
                  }

      }

}

class MyClass{
      String st;
      float ft;
      public MyClass(String st,float ft) {
            // TODO Auto-generated constructor stub
            this.st=st;
            this.ft=ft;
      }
     
}
මේ ගැන තව උදාහරණ පහත ලින්ක් වලින් බලාගන්න පලුවන්.

අපි දැන් බලමු file operation ටිකක් කරන්න පොඩි programme කිහිපයක්.
import java.io.File;


public class file1 {

      /**
       * @param args
       */
      public static void main(String[] args) {
            // TODO Auto-generated method stub
            File f=new File("Path");
            if(f.isDirectory()){
                  System.out.println("Given file is:"+f.isDirectory());
            }
           
      }

}
මේ programme එකින් කරන්නේ file එකක් load කරලා එක Directory එකක්ද කියල බලනවා.path කියන තැනට file එක තියන තැන හරියටම path එක දෙන්න ඕනේ.අපිට file class එකේ තියන methodes , isDirectory() වගේ use කරලා විවිද වැඩ කරගන්න පලුවන්.ඔයගොල්ලොන්ට අනිත් method ඕනනම් API එක use කරලා බලන්න.

දැන් අපි තව උදාහරණයක් බලමු.

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;


public class file1 {

      /**
       * @param args
       */
      public static void main(String[] args) {
            // TODO Auto-generated method stub
            try {
                  BufferedReader buffer=new BufferedReader(new FileReader("file Path"));
                  buffer.read();
                  buffer.readLine();
                  buffer.close();
            } catch (IOException e) {
                  // TODO Auto-generated catch block
                  e.printStackTrace();
            }
           
      }

}
මේ programme එකේ BufferReader එකක් use කරලා තමයි file එක buffer කරගන්නෙ.එටපස්සේ පලුවන් method use කරලා විවිද වැඩ ගන්න පලුවන්.
මේවගේ අනිත් IO class use කරන්න පලුවන්.මං හිතන්නේ මේ පොස්ට් එකින් ඔයාලට Input and Output Streams ගැන පොඩි දැනුමක් එන්න ඇති කියල.නැවත අලුත් පොස්ට් එකකින් හමුවෙමු....

No comments: