Essential Java.io Classes

Discussion in 'Java' started by shabbir, Jul 6, 2014.

  1. shabbir

    shabbir Administrator Staff Member

    Joined:
    Jul 12, 2004
    Messages:
    15,375
    Likes Received:
    388
    Trophy Points:
    83
    Java.io package provides classes for system input and output through data streams, serialization and the file system. Some of important and popular classes of java.io package are given below:

    Java.io.BufferedInputStream Class



    The Java.io.BufferedInputStream class adds functionality to another input stream.
    • When the BufferedInputStream is created, an internal buffer array is created.
    • As bytes from the stream are read or skipped, the internal buffer is refilled as necessary from the contained input stream, many bytes at a time.
    Class declaration
    Code:
    public class BufferedInputStream
       extends FilterInputStream
    
    Class constructors
    1. BufferedInputStream(InputStream inpstr) - Creates a BufferedInputStream and saves its argument, the input stream inpstr, for later on use.
    2. BufferedInputStream(InputStream inpstr, int size) - Creates a BufferedInputStream with the specific buffer size, and saves its argument, the input stream inpstr, for later use.
    Class methods
    1. int available() - Returns an approximate number of bytes that can be read from this input stream.
    2. void close() - Closes this input stream and releases any system resources associated with the stream.
    3. int read() - Reads next byte of data from the input stream.
    4. int read(byte[] b, int off, int len) - Reads bytes from this input stream into the specified byte array, starting at the given offset.
    5. void reset() - Repositions this stream to the position at the time; mark method was last called on this input stream.
    6. long skip(long n) - This method skips over and discards n bytes of data from this input stream.
    Example
    Code:
    import java.io.BufferedInputStream;
    import java.io.FileInputStream;
    import java.io.InputStream;
    
    public class BufferedInputStreamDemo {
       public static void main(String[] dt) throws Exception {
    
    //  initialize InputStream and BufferedInputStream
          InputStream is = null;
          BufferedInputStream bis = null;
    
          try{
           // open InputStream from input.txt to read data
             	is = new FileInputStream("E:/javaprog/input.txt");
             	bis = new BufferedInputStream(is);
    
          // get the number of bytes from steam available
             	int numByte = bis.available();
          //  create new byte array of given size
        	byte[] buf = new byte[numByte];
    
       //   reads byte into buffer from offset 3 and will read 10 bytes	 
             bis.read(buf, 3, 10);
             
             for (byte b : buf) {
                System.out.println((char)b+": " + b);
             }
             }catch(Exception e){
                e.printStackTrace();
             }finally{
                //  release all the resources here
                if(is!=null)
                   is.close();
                if(bis!=null)
                   bis.close();
          }	
       }
    }
    Output

    [​IMG]

    Java.io.BufferedOutputStream Class



    The Java.io.BufferedOutputStream class implements a buffered output stream. It sets up an output stream so that an application can write bytes to the underlying output stream.

    Class declaration
    Code:
    public class BufferedOutputStream
       extends FilterOutputStream
    
    Class constructors
    1. BufferedOutputStream(OutputStream out) - Creates a new buffered output stream that helps to write data to the particular output stream.
    2. BufferedOutputStream(OutputStream out, int size) - Creates a new buffered output stream that helps to write data to the particular output stream with the specified buffer size.
    Class methods
    1. void flush() - Buffered output stream is flushed using this method.
    2. void write(byte[] b, int off, int len) - Len bytes from the specified byte array are writen starting at offset off to buffered output stream.
    3. void write(int b) - Specified byte to this buffered output stream is written by this method.
    Example
    Code:
    import java.io.BufferedOutputStream;
    import java.io.ByteArrayOutputStream;
    import java.io.IOException;
    public class BufferedOutputStreamDemo {
       public static void main(String[] args) throws Exception {
    
    //  initialize ByteArrayOutputStream and BufferedOutputStream
          ByteArrayOutputStream bas = null;
          BufferedOutputStream bos = null;
          try{
    //  create new output stream 
             bas = new ByteArrayOutputStream();
             bos = new BufferedOutputStream(bas);
    
    //  define byte array
             byte[] bytes = {11, 21, 31, 41, 51};
    
    //  write byte array to the output stream
             bos.write(bytes, 0, 5);
             bos.flush();
             for (byte b:bas.toByteArray())
             {
                System.out.print(b+" ");
             }
          }catch(IOException e){
             e.printStackTrace();
          }finally{
    //  release all the resources here.
             if(bas!=null)
                bas.close();
             if(bos!=null)
                bos.close();
          }
       }
    }
    Output

    [​IMG]

    Java.io.BufferedReader Class



    The Java.io.BufferedReader class reads text from a character-input stream so that characters, arrays, and lines can be read efficient.
    • The default buffer size may be used or we can specify buffer size.
    • Each read request made of a Reader causes a corresponding read request to be made of the underlying character or byte stream.
    Class declaration
    Code:
    public class BufferedReader
       extends Reader
    
    Class constructors
    1. BufferedReader(Reader in) - Buffering character-input stream is created that uses a default-sized input buffer.
    2. BufferedReader(Reader in, int sz) - Buffering character-input stream is created that uses an input buffer of the specified size.
    Class methods
    1. void close() - Stream is being closed and releases any system resources associated with it.
    2. int read() - Reads a single character.
    3. int read(char[] cbuf, int off, int len) - Reads characters into a part of an array.
    4. String readLine() - Reads a line of text.
    5. boolean ready() - Tells whether stream is ready to be read or not.
    6. void reset() - Resets the stream.
    Example
    Code:
    
    import java.io.InputStreamReader;
    import java.io.BufferedReader;
    class KeyboardInput
    {
    	public static void main(String dt[])
    	{
    		InputStreamReader isr= null;
    		BufferedReader br= null;
    		int a=0,b=0,c=0;
    		try
    		{
    		     //  open input stream for reading data
    			isr= new InputStreamReader(System.in);
    			br=new BufferedReader(isr);
    			System.out.println("Enter 1st number =");
    			a= Integer.parseInt(br.readLine());
    			System.out.println("Enter 2nd number =");
    			b= Integer.parseInt(br.readLine());
    			c=a+b;
    			System.out.println("Result ="+c);
    		}
    		catch (Exception e)
    		{
    			System.out.println(e);
    		}
    		finally
    		{
    		   //   release all the resources.
    			try
    			{
    				br.close();
    				isr.close();
    			}
    			catch(Exception e)
    			{
    				System.out.println(e);
    			}
    		}
    	}
    }
    
    Output

    [​IMG]

    Java.io.File Class



    The Java.io.File class is an abstract representation of file and directory pathnames.
    • Restrictions may be implemented to a file system to certain operations on the actual file-system object, such as reading, writing, and executing. These restrictions are known as access permissions.
    • Instances of the File class are immutable; i.e., once created, the abstract pathname represented by a File object will never change.
    Class declaration
    Code:
    public class File
      extends Object
        implements Serializable, Comparable<File>
    
    Class constructors
    1. File(File parent, String child) - Creates new file instance from a parent abstract path name and a child path name string is created.
    2. File(String pathname) - Given pathname string is converted into an abstract path name and thus a new file instance is created.
    3. File(String parent, String child) - New File instance from a parent pathname string and a child pathname string is created.
    4. File(URI uri) - Converts the given file: URI into an abstract pathname and Creates a new File instance.
    Class methods
    1. boolean delete() - File or directory denoted by this abstract pathname is deleted.
    2. boolean equals(Object obj) - Abstract pathname for equality with the given object is being tested.
    3. boolean exists() - Tests whether the file or directory denoted by this abstract pathname exists or not.
    4. File getAbsoluteFile() - Absolute form of the abstract pathname is returned.
    5. String getAbsolutePath() - Absolute pathname string of this abstract pathname is returned.
    6. String getName() - Name of file/directory denoted by this abstract pathname is returned.
    7. String getParent() - Returns the pathname string of this abstract pathname's parent, or null if this pathname does not name a parent directory.
    8. String getPath() - Abstract pathname is converted into a pathname string.
    9. boolean isAbsolute() - Tests whether this abstract pathname is absolute or not.
    10. boolean isDirectory() - Tests whether the file denoted by this abstract pathname is a directory.
    11. boolean isFile() - Tests whether the file denoted by this abstract pathname is valid or not.
    12. boolean isHidden() - Tests whether the file named by this abstract pathname is hidden or not.
    13. long length() - Length of the file denoted by this abstract pathname is returned.
    14. boolean mkdir() - Directory named by this abstract pathname is created.
    15. boolean renameTo(File dest) - The file denoted by this abstract pathname is renamed.
    Example
    Code:
    import java.io.File;
    public class FileDemo {
       public static void main(String[] dt) {
         File f = null;
          File f1 = null;
          String path = "";
          boolean b = false;
          try{      
              	f = new File("myfile.txt");
             //  creates new file
    	f.createNewFile();
            //  get absolute path a file
    	f1 = f.getAbsoluteFile();
            //  check whether file exists or not
             	b = f1.exists();
             path = f1.getAbsolutePath();
             if(b)
             {
                System.out.print(f.getName()+" exists at "+ path);
             }
          }catch(Exception e){
             e.printStackTrace();
          }
       }
    }
    Output

    [​IMG]

    Java.io.FileReader Class



    The Java.io.FileReader class is a convenient class for reading character files.
    • The constructors of this class assume that the default character encoding and the default byte-buffer size is appropriate.
    • FileReader is for reading streams of characters. FileInputStream is used for reading streams of raw bytes.
    Class declaration
    Code:
    public class FileReader
       extends InputStreamReader
    
    Class constructors
    • FileReader(File file) - New FileReader is created, and reads from the given file.
    • FileReader(FileDescriptor file) - New FileReader is created, and reads from the given FileDescriptor.
    • FileReader(String fileName) - This constructor creates the new FileReader and reads from the given file name.
    Class Methods

    Java.io.FileReader class inherits methods from the following classes:
    • Java.io.InputStreamReader
    • java.uti.Reader
    Example
    Code:
    import java.io.FileReader;
    class FileReaderDemo
    {
    	public static void main(String arr[])
    	{
    		FileReader fr=null;
    		try
    		{
    		     // create new FileReader to read from a given file
    			fr=new FileReader("wyz.txt");
    			int a =0;
    			while((a=fr.read()) != -1)
    			{
    			        System.out.print((char)a);
    			}
    		}
    		catch(Exception e)
    		{
    			System.out.println(e);
    		}
    		finally
    		{
    			try
    			{
    				fr.close();
    			}
    			catch(Exception e)
    			{
    			System.out.println(e);
    			}	
    		}
    	}
    }
    
    Output

    [​IMG]

    Java.io.FileWriter Class



    The Java.io.FileWriter class is a convenient class for writing character files.
    • The constructors of this class assume that the default character encoding and the default byte-buffer size are acceptable.
    • FileWriter is used for writing streams of characters. FileOutputStream is used for writing streams of raw bytes.
    Class declaration
    Code:
    public class FileWriter
       extends OutputStreamReader
    
    Class constructors
    1. FileWriter(File file) - Constructs a new FileWriter object to write a given File passed as argument.
    2. FileWriter(File file, boolean append) - Creates a new FileWriter object to append a given File passed as an argument.
    3. FileWriter(FileDescriptor fd) - FileWriter object linked with a file descriptor is created.
    4. FileWriter(String fileName) - FileWriter object writes to the String file name passed as an argument.
    Class Methods
    This class inherits methods from the following classes:
    • Java.io_OutputStreamWriter
    • java.uti.Writer
    Example
    Code:
    import java.io.FileWriter;
    class FileWriterDemo
    {
    	public static void main(String arr[])
    	{
    		FileWriter fw=null;
    		try
    		{
    		    //  creates a new FileWriter object
    			fw=new FileWriter("wyz.txt",true);
    			fw.write("hello");
    			fw.write("how");
    			fw.write("are");
    			fw.write("you");
    		}
    		catch(Exception e)
    		{	System.out.println(e);
    		}
    		finally
    		{
    		   //  release all the resources here.
    			try
    			{	fw.close();
    			}
    			catch(Exception e)
    			{	System.out.println(e);
    			}	
    		}
    	}
    }

    Java.io.InputStreamReader Class



    The Java.io.InputStreamReader class is a bridge from byte streams to character streams. This class reads bytes and decodes them into characters using a specified charset.

    Class declaration
    Code:
    public class InputStreamReader
       extends Reader
    
    Class constructors
    1. InputStreamReader(InputStream in) - InputStreamReader is created which uses the default charset.
    2. InputStreamReader(InputStream in, Charset cs) - InputStreamReader is created which uses the given charset.
    3. InputStreamReader(InputStream in, String charsetName) - InputStreamReader is created which uses the name charset.
    Class methods
    1. void close() - Stream is closed and any system resources associated with it are released.
    2. int read() - Reads a single character.
    3. int read(char[] cbuf, int offset, int length) - Reads characters into a part of an array.
    4. boolean ready() - Tells whether this stream is ready to be read or not.
    Example: Refer to BufferedReader class
     
    Last edited: Jan 21, 2017

Share This Page

  1. This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
    By continuing to use this site, you are consenting to our use of cookies.
    Dismiss Notice