Results 1 to 5 of 5

Thread: JAVA Fundamental: The java.io package

  1. #1
    Join Date
    Nov 2008
    Posts
    202

    JAVA Fundamental: The java.io package

    This tutorial aims to present the package java.io describing the different classes within them and by specifying when and how to use them. By going through this tutorial you will explore classes in java.io more clearly. This tutorial is about the basic java I/O classes and one can implement java.io package more than this.

    Introduction

    An input / output in Java is to exchange data between the program and another source that can be like, memory, a file or the program itself. To achieve this, Java employs what is called a stream (i.e flow of data) between the source and destination data. Any transaction input / output in Java follows the following pattern:

    - Opening a stream
    - Reading or writing data
    - Close the streams

    The java.io package provides all the necessary classes to create, read and write the data, from the destination to the source.

    The java.io package

    There are several kinds of flows that can be classified according to several criteria

    - There are inflows and outflows
    - The flow of characters and the binary stream (because as Java uses uni-code so characters are coded 2 bytes, not one)
    - The communication flow and process flow
    - The flows with or without buffer

    In this tutorial first the Bytestream flow of communication is explained and then the Character flow of communication is explained.

    A] The Byte Streams

    The bytestreams are used, as the name implies to handle bytes, that is to say that is exchanged between the bytes program and another entity outside it. Such flow can be used to load images into memory or to save them to disk, they are also used for register objects (a process called serialization) or loading (de-serialization).

    The bytestreams are derived from two main abstract classes:

    - InputStream : for the input stream.
    - OutputStream : to the output stream.

    Both classes are abstract. Mostly these classes are not directly but with their subclasses. Note the presence of a number of methods, namely the different methods write for OutputStream and different methods read for InputStream.

    A-1] The Input Stream

    The InputStream can be classified into two categories

    - The flow of communication (data) is focused on creation between the program and the another entity.
    - The flow of treatment is the process of data exchange between two nodes.

    Here are some of the classes most commonly used for InputStream

    A-1.a] FileInputStream

    It creates a stream with a file from the file system. This class has a Constructor taking as parameter an object of type File and a another taking a String as a parameter, which represents the path to the file. Here is some code to load the binary content of a file and display it on standard output (that is the console)
    Code:
    import java.io. *;
    
    Public class TFileInputStream {
    	Public static void hand(String [] args){
    		FileInputStream flinstr;
    		int bt;
    		try{
    			//creation a flow Input with for source a file appointed 			
    			//source, this instantiation may remove a except of type 				
    			//FileNotFound
    			flinstr=new FileInputStream("source");
    			//the method read () returns a int representative byte read the worth (-1) 			
    			//represents the end of file.
    			// read may remove a except of type IOException
    			try{
    				while((bt=flinstr.read())!= -1){  
    					System.out.System.out.println(bt);
    				}
    			}
    			//Do not forget of close the flow to of RELEASE the Resources it 			
    			//uses
    			finally{
    				flinstr.close();
    			}
    		}
    		catch(FileNotFoundException ef){
    			System.out.System.out.println("file Not Found");
    		}
    		catch(IOException e){
    			System.out.System.out.println(e+"mistake at of the reading of file");
    		}
    	}
    }
    A-1.b] ByteArrayInputStream

    It can read binary data from a byte array. The source of this flow is the program itself. Here is a sample code illustrating its use.
    Code:
    import java.io. *;
    Public class TestByteArrayInputStream {
    	Public static void hnd(String [] args){
    		ByteArrayInputStream bis;
    		int bty;
    		byte[] buff=new byte[10];
    		//filling of buffer
    		for(byte i=0, i<10, i++) {
    			buffer [i]=i;
    		}
    		//creation a flow Input with for source a board of bytes, here 				
    		//buffer
    		bis=new ByteArrayInputStream(buffer);
    		//reading of flow.
    		// note that the values returned are of type int and no of type byte
    		while((bty=bis.read())!=-1) {
    			System.out.System.out.println(bty);
    		}
    	}
    }
    A-1.c] BufferedInputStream

    This class allows reading of data using a buffer. When instantiated, a table of bytes is created to serve as a buffer. This table is automatically re-sized to each reading to contain data from the input stream. Here is the same code for it.
    Code:
    import java.io. *;
    
    Public class TestBufferedInputStream {
    	Public static void hand(String [] args){
    		BufferedInputStream bufinstr;
    		int byt;
    Byte [] buffer;
    		try{
    			//creation a BufferedInputStream on a InputStream with for 			
    			//source a file appointed source
    
    			bufinstr=new BufferedInputStream(new FileInputStream("source"));
    			//the method available Permet of know the number of bytes who 			
    			//may Must be a read a way no blocking.
    
    			System.out.System.out.println(bufinstr.available());
    			//reading of data
    			System.out.System.out.println("start reading");
    			try{
    				long chr=System.currentTimeMillis();
    				while((byt=bufinstr.read())!=-1);
    			System.out.System.out.println("end reading");
    			System.out.System.out.println("duration ="+(System.out.printlncurrentTimeMillis()-chr));
    			}
    			finally{
    				//not not forget of close the flow
    				bufinstr.close();
    			}
    		}catch(FileNotFoundException ef){
    			System.out.System.out.println("file Not Found");
    		}
    		catch(IOException e){
    			System.out.System.out.println(e);
    		}
    	}
    }
    A-1.d] DataInputStream

    This is used to read data representing the types Java primitives (int, boolean, double, byte etc) Thus, this class has methods like readInt (), readBoolean () etc.

    A-1.e] SequenceInputStream

    It can concatenate two or more InputStream. The reading is sequential, beginning with the first and passing the following as soon as we reached the end of the current stream, while calling its method close ().

    A-1.f] ObjectInputStream

    It can "serialize" an object, that is to say, restore an object previously saved using a ObjectOutputStream. The serialization will view more details when addressing the class ObjectOutputStream.

  2. #2
    Join Date
    Nov 2008
    Posts
    202

    Re: JAVA Fundamental: The java.io package

    A-2] The Output Stream

    For each input stream there is an output stream. This part should not be difficult to understand as these are opposite (some what) to the classes mentioned above.

    Here are some of the classes most commonly used for OutputStreams

    A-2.a] FileOutputStream

    This class allows writing sequential data in a file. Here an sample code for this.
    Code:
    import java.io. *;
    Public class CopyFileSimple {
        Public static void hand(String [] args){
            FileInputStream flinstr;
    FileOutputStream flotstr;
            int byt;
            try{
                    //creation a flow Input with for source a file appointed             
                    //source, this instantiation may remove a except of type                 
                    //FileNotFound
                    flinstr=new FileInputStream("source");
                    try {
                        flotstr=new FileOutputStream("dist");
                        try {
                            
                            while((byt=flinstr.read())!=-1) {
                                flotstr.write(byt);
                            }
                        }finally{
                            //we farm flotstr
                            flotstr.close();
                        }
                    }
                    finally{
                        //we release the Resources in closing flinstr
                        flinstr.close();
                    }
            }catch(FileNotFoundException ef){
                System.out.System.out.println("file Not Found");
            }
            catch(IOException e){
                System.out.System.out.println(e);
            }
        }
    }
    A-2.b] ByteArrayOutputStream

    It can write data into a buffer whose size fits based on need. We can recover data written with the method toByteArray() or toString(). Here is the sample code for this.
    Code:
    import java.io. *;
    Public class TestByteArrayOutputStream {
        Public static void hand(String [] args){
            ByteArrayOutputStream byotstr=new ByteArrayOutputStream();
            int bty;
            byte[] Tab=new byte[10];
            
            for(byte i=0, i<10, i++) {
                byotstr.write(i);
            }
            //recovery of data contained in the buffer
            tab=byotstr.toByteArray();
            //view of data
            for(int j=0j<10j++) {
                System.out.System.out.println(tab [j]);
            }
        }
    }
    A-2.c]BufferedInputStream

    This class can write in a buffer and then write the stamp on the entire file instead of writing byte by byte file. Here is an sample code for it.
    Code:
    import java.io. *;
    Public class TestBufStr {
        Public static void hand(Strbuffing [] args){
            int i;
            try{
                //creation of flow
                BufferedInputStream buffin=new BufferedInputStream(new FileInputStream("source"));
                try{
                    BufferedOutputStream out=new BufferedInputStream(new FileOutputStream("dist"));
                    //Copy of file
                    try{
                        while((i=buffin.read())!=-1) {
                            out.write(i);
                        }
                        
                        out.flush();
                    }finally{
                        //close of out
                        out.close();
                    }
                }
                finally{    
                    //close of buffin
                    buffin.close();
                }
            }
            catch(IOException e){
                System.out.System.out.println(e);
            }
        }
    }
    A-2.d]DataOutputStream

    This class allows writing data format Java provides portability inter-application and inter-systems. Here is a sample code for it.
    Code:
    import java.io. *;
    
    Public class TestDataInputStream {
        Public static void hand(String [] args){
            try{
                //creation of flow
                DataInputStream in=new DataInputStream(new FileInputStream("Release"));
                
                //data to read
                boolean ts;
                int i;
                try{
                    //reading of data
                    ts=in.readBoolean();
                    i=in.readInt();
                }
                finally{
                    //close the flow
                    in.close();
                }
                //view of data
                System.out.System.out.println(ts);
    System.out.System.out.println(i);
                
            }
            catch(IOException e){
                System.out.System.out.println(e);
            }
        }
    }

  3. #3
    Join Date
    Nov 2008
    Posts
    202

    Re: JAVA Fundamental: The java.io package

    B] The Character Streams

    On common question asked - Why feed the special characters while these are binary data? The answer is that Java, unlike many other languages, use Unicode. Thus, the characters are coded on 16 bits instead of 8. These flows are therefore manage charsets (possible conversion from one game to another). There are two main abstract classes the Reader class and the Writer class.

    - Reader : reads characters from a source
    - Writer : writes characters to the destination

    B-1] The Reader Class

    Most of the subclasses extend to the most abstract class Reader and define the method read(). This methods is used to read data from a source in the character format.

    Here are the classes most commonly used

    B-1.a] CharArrayReader

    This class is equivalent to ByteArrayInputStream for characters. It also uses a buffer for the indexed Reading characters. Here is an sample code for it.
    Code:
    import java.io. *;
    
    Public class TestCharArrayReader {
        Public static void hand(String [] args){
            try{
                char[] test={'has','b','c','d','e'};
                
                //creation of flow
                CharArrayReader charrd=new CharArrayReader(SO);
                
                //reading and view of data
                for(int i=0, i < 5, i++){
                    System.out.System.out.println((char) charrd.read());
                }
                
            }catch(IOException e){
                System.out.System.out.println(e);
            }
        }
    }
    B-1.b] FileReader

    Class is certainly the most important because it certainly the most used. It extends InputStreamReader and uses the buffer and the default encoding. It is therefore in most cases. If you need another encoding must be extend InputStreamReader. Here is an sample code for it.
    Code:
    import java.io. *;
    
    Public class TestFileReader {
        Public static void hand(String [] args){
            try{
                int i;
                //creation of flow
                FileReader flread=new FileReader("source");
                try{
                    //reading and view of data
                    while((i=flread.read())!=-1){
                        System.out.System.out.println((char) i);
                    }
                }
                finally{
                    flread.close();
                }
            }
            catch(IOException e){
                System.out.System.out.println(e);
            }
        }
    }
    B-1.d] InputStreamReader

    This class can transform a stream of binary data into a stream of characters. It is very useful when the buffer or the encoding default FileReader not suitable. It has a constructor that takes parameters an input stream of binary data and a Charset (object used to define the encoding use). The method read () reads the number required bytes constituting one character.

    B-1.e] BufferedReader:

    This class allows the use of a stamp (which can specify the size) when reading a stream of characters. It is very useful for improving performance the read operation. Its use is similar to that of BufferedInputStream.

  4. #4
    Join Date
    Nov 2008
    Posts
    202

    Re: JAVA Fundamental: The java.io package

    B-2] The Writer Class

    Each input stream represents an output stream except for Class LineNumberReader. They extend all the class Writer and redefined, The method write (), method Flush () which empties the buffer by forcing effective writing.

    Here are some of the most commonly used classes

    B-2.a] BufferedWriter

    This class allows the use of a buffer, So you can write characters per block. Here is an sample code for this.
    Code:
    import java.io. *;
    Public class TestBufferedWriter {
        Public static void hand(String [] args){
            try{
                String line;
                //creation of flow
                BufferedReader in=new BufferedReader(new FileReader("source"));
                //reading and Copy of data
                try{
                    BufferedWriter buffwrt=new BufferedWriter(new FileWriter("dist"));
                    try{    
                        while((line=in.readLine())!=null){
                        buffwrt.write(line);
                        //insert a jump of row a way Mobile
                        buffwrt.newLine();
                        }
                        buffwrt.flush(); //empty the buffer
                    }finally{
                        //close
                        buffwrt.close();
                    }
                }
                finally{
                    in.close();
                }
            }
            catch(IOException e){
                System.out.println(e);
            }
        }
    }
    B-2.b] CharArrayWriter

    This class allows the writing of characters in buffer ranging in size to contain the data. Note that the method close () has no effect on an instance of this class and call other methods after close () do not lift of IOException.

    B-2.c] StringWriter

    This class allows the writing of characters in a StringBuffer. Its content can be obtained as String through the method toString ().

    B-2.d] PipedWriter

    This class creates a pipe or moving the characters by connecting to an object type PipedReader.

    B-2.e] FileWriter

    It is suitable for most cases writing in a file, its operation is the opposite of FileReader. But it also uses buffer and encoding by default.

  5. #5
    Join Date
    Nov 2008
    Posts
    202

    Re: JAVA Fundamental: The java.io package

    Summary:

    Here is a summary of the different classes we have seen so far. However I opted for another way to classify to know the destination.


    Conclusion:

    It is clear from this tutorial that java.io API is a very complete with which it is possible to do infinite things and will suit most needs input / output. I invite you still watching those few classes which certainly are not part of java.io, but nevertheless serve to manipulate flows. I mean: CheckedInputStream , InflaterInputStream and its three subclasses GZIPInputStream, ZipInputStream, and JarInputStream and their counterparts for the output stream. All these classes are part of the package java.util.zip. This conclusion would have been incomplete without the mention of package java.nio and its sub-packages which has been created to increase performance. I hope this article helped you better understand java.io. Please feel free to give comments.

Similar Threads

  1. Replies: 4
    Last Post: 04-09-2013, 11:04 PM
  2. Replies: 5
    Last Post: 18-06-2011, 09:33 PM
  3. Java - scanner package for user input
    By Shaan12 in forum Software Development
    Replies: 4
    Last Post: 21-07-2010, 02:49 PM
  4. How to package in java
    By nanakofiboafo in forum Software Development
    Replies: 3
    Last Post: 22-04-2009, 08:29 AM

Tags for this Thread

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
Page generated in 1,713,442,786.29730 seconds with 17 queries