Java I/O and File

By ukmodak | March 31st 2024 10:34:01 AM | viewed 743 times

Java I/O Tutorial

Java I/O (Input and Output) is used to process the input and produce the output

Java uses the concept of a stream to make I/O operation fast. The java.io package contains all the classes required for input and output operations.

We can perform file handling in Java by Java I/O API.

Stream

A stream is a sequence of data. In Java, a stream is composed of bytes. It's called a stream because it is like a stream of water that continues to flow.

In Java, 3 streams are created for us automatically. All these streams are attached with the console.

  • 1) System.out: standard output stream
  • 2) System.in: standard input stream
  • 3) System.err: standard error stream

Let's see the code to print output and an error message to the console.

    System.out.println("simple message");  
    System.err.println("error message");  

Let's see the code to get input from console.

    int i=System.in.read();//returns ASCII code of 1st character  
    System.out.println((char)i);//will print the character  

OutputStream vs InputStream

The explanation of OutputStream and InputStream classes are given below:

OutputStream

Java application uses an output stream to write data to a destination; it may be a file, an array, peripheral device or socket.

InputStream

Java application uses an input stream to read data from a source; it may be a file, an array, peripheral device or socket. Let's understand the working of Java OutputStream and InputStream by the figure given below.

OutputStream class

OutputStream class is an abstract class. It is the superclass of all classes representing an output stream of bytes. An output stream accepts output bytes and sends them to some sink.

Useful methods of OutputStream

Method Description
1) public void write(int)throws IOException is used to write a byte to the current output stream.
2) public void write(byte[])throws IOException is used to write an array of byte to the current output stream.
3) public void flush()throws IOException flushes the current output stream.
4) public void close()throws IOException is used to close the current output stream.

OutputStream Hierarchy

InputStream class

InputStream class is an abstract class. It is the superclass of all classes representing an input stream of bytes.

Useful methods of InputStream

Method Description
1) public abstract int read()throws IOException reads the next byte of data from the input stream. It returns -1 at the end of the file.
2) public int available()throws IOException returns an estimate of the number of bytes that can be read from the current input stream.
3) public void close()throws IOException is used to close the current input stream.

InputStream Hierarchy

Java FileOutputStream Class

Java FileOutputStream is an output stream used for writing data to a file.

If you have to write primitive values into a file, use FileOutputStream class. You can write byte-oriented as well as character-oriented data through FileOutputStream class. But, for character-oriented data, it is preferred to use FileWriter than FileOutputStream.

FileOutputStream class declaration

Let's see the declaration for Java.io.FileOutputStream class:

    public class FileOutputStream extends OutputStream  

FileOutputStream class methods

Method Description
protected void finalize() It is used to clean up the connection with the file output stream.
void write(byte[] ary) It is used to write ary.length bytes from the byte array to the file output stream.
void write(byte[] ary, int off, int len) It is used to write len bytes from the byte array starting at offset off to the file output stream.
void write(int b) It is used to write the specified byte to the file output stream.
FileChannel getChannel() It is used to return the file channel object associated with the file output stream.
FileDescriptor getFD() It is used to return the file descriptor associated with the stream.
void close() It is used to closes the file output stream.

Java FileOutputStream Example 1: write byte

    import java.io.FileOutputStream;  
    public class FileOutputStreamExample {  
        public static void main(String args[]){    
               try{    
                 FileOutputStream fout=new FileOutputStream("D:\\testout.txt");    
                 fout.write(65);    
                 fout.close();    
                 System.out.println("success...");    
                }catch(Exception e){System.out.println(e);}    
          }    
    }  

Output:

Success...

The content of a text file testout.txt is set with the data A.

testout.txt

A

Java FileOutputStream example 2: write string

    import java.io.FileOutputStream;  
    public class FileOutputStreamExample {  
        public static void main(String args[]){    
               try{    
                 FileOutputStream fout=new FileOutputStream("D:\\testout.txt");    
                 String s="Welcome to javaTpoint.";    
                 byte b[]=s.getBytes();//converting string into byte array    
                 fout.write(b);    
                 fout.close();    
                 System.out.println("success...");    
                }catch(Exception e){System.out.println(e);}    
          }    
    }  

Output:

Success...

The content of a text file testout.txt is set with the data Welcome to javaTpoint.

testout.txt

Welcome to javaTpoint.

Java FileInputStream Class

Java FileInputStream class obtains input bytes from a file. It is used for reading byte-oriented data (streams of raw bytes) such as image data, audio, video etc. You can also read character-stream data. But, for reading streams of characters, it is recommended to use FileReader class.

Java FileInputStream class declaration

Let's see the declaration for java.io.FileInputStream class:

    public class FileInputStream extends InputStream  

Java FileInputStream class methods

Method Description
int available() It is used to return the estimated number of bytes that can be read from the input stream.
int read() It is used to read the byte of data from the input stream.
int read(byte[] b) It is used to read up to b.length bytes of data from the input stream.
int read(byte[] b, int off, int len) It is used to read up to len bytes of data from the input stream.
long skip(long x) It is used to skip over and discards x bytes of data from the input stream.
FileChannel getChannel() It is used to return the unique FileChannel object associated with the file input stream.
FileDescriptor getFD() It is used to return the FileDescriptor object.
protected void finalize() It is used to ensure that the close method is call when there is no more reference to the file input stream.
void close() It is used to closes the stream.

Java FileInputStream example 1: read single character

    import java.io.FileInputStream;  
    public class DataStreamExample {  
         public static void main(String args[]){    
              try{    
                FileInputStream fin=new FileInputStream("D:\\testout.txt");    
                int i=fin.read();  
                System.out.print((char)i);    
      
                fin.close();    
              }catch(Exception e){System.out.println(e);}    
             }    
            }  

Note: Before running the code, a text file named as "testout.txt" is required to be created. In this file, we are having following content:
Welcome to javatpoint.

After executing the above program, you will get a single character from the file which is 87 (in byte form). To see the text, you need to convert it into character.

Output:

W

Java FileInputStream example 2: read all characters

    package com.javatpoint;  
      
    import java.io.FileInputStream;  
    public class DataStreamExample {  
         public static void main(String args[]){    
              try{    
                FileInputStream fin=new FileInputStream("D:\\testout.txt");    
                int i=0;    
                while((i=fin.read())!=-1){    
                 System.out.print((char)i);    
                }    
                fin.close();    
              }catch(Exception e){System.out.println(e);}    
             }    
            }  

Output:

Welcome to javaTpoint

Java BufferedOutputStream Class

Java BufferedOutputStream class is used for buffering an output stream. It internally uses buffer to store data. It adds more efficiency than to write data directly into a stream. So, it makes the performance fast.

For adding the buffer in an OutputStream, use the BufferedOutputStream class. Let's see the syntax for adding the buffer in an OutputStream

    OutputStream os= new BufferedOutputStream(new FileOutputStream("D:\\IO Package\\testout.txt"));  

Java BufferedOutputStream class declaration

Let's see the declaration for Java.io.BufferedOutputStream class:

    public class BufferedOutputStream extends FilterOutputStream  

Java BufferedOutputStream class constructors

Method Description
BufferedOutputStream(OutputStream os) It creates the new buffered output stream which is used for writing the data to the specified output stream.
BufferedOutputStream(OutputStream os, int size) It creates the new buffered output stream which is used for writing the data to the specified output stream with a specified buffer size.

Java BufferedOutputStream class methods

Method Description
void write(byte[] b, int off, int len) It write the bytes from the specified byte-input stream into a specified byte array, starting with the given offset
void flush() It flushes the buffered output stream.

Example of BufferedOutputStream class:

In this example, we are writing the textual information in the BufferedOutputStream object which is connected to the FileOutputStream object. The flush() flushes the data of one stream and send it into another. It is required if you have connected the one stream with another.

    package com.javatpoint;  
    import java.io.*;  
    public class BufferedOutputStreamExample{    
    public static void main(String args[])throws Exception{    
         FileOutputStream fout=new FileOutputStream("D:\\testout.txt");    
         BufferedOutputStream bout=new BufferedOutputStream(fout);    
         String s="Welcome to javaTpoint.";    
         byte b[]=s.getBytes();    
         bout.write(b);    
         bout.flush();    
         bout.close();    
         fout.close();    
         System.out.println("success");    
    }    
    }  

Output:

Success

testout.txt

Welcome to javaTpoint.

Java BufferedInputStream Class

Java BufferedInputStream class is used to read information from stream. It internally uses buffer mechanism to make the performance fast.

The important points about BufferedInputStream are:

  • When the bytes from the stream are skipped or read, the internal buffer automatically refilled from the contained input stream, many bytes at a time.
  • When a BufferedInputStream is created, an internal buffer array is created.

Java BufferedInputStream class declaration

Let's see the declaration for Java.io.BufferedInputStream class:

     public class BufferedInputStream extends FilterInputStream  
 

Java BufferedInputStream class constructors

Constructor Description
BufferedInputStream(InputStream IS) It creates the BufferedInputStream and saves it argument, the input stream IS, for later use.
BufferedInputStream(InputStream IS, int size) It creates the BufferedInputStream with a specified buffer size and saves it argument, the input stream IS, for later use.

Java BufferedInputStream class methods

Method Description
int available() It returns an estimate number of bytes that can be read from the input stream without blocking by the next invocation method for the input stream.
int read() It read the next byte of data from the input stream.
int read(byte[] b, int off, int ln) It read the bytes from the specified byte-input stream into a specified byte array, starting with the given offset.
void close() It closes the input stream and releases any of the system resources associated with the stream.
void reset() It repositions the stream at a position the mark method was last called on this input stream.
void mark(int readlimit) It sees the general contract of the mark method for the input stream.
long skip(long x) It skips over and discards x bytes of data from the input stream.
boolean markSupported() It tests for the input stream to support the mark and reset methods.

Example of Java BufferedInputStream

Let's see the simple example to read data of file using BufferedInputStream:

    package com.javatpoint;  
       
    import java.io.*;  
    public class BufferedInputStreamExample{    
     public static void main(String args[]){    
      try{    
        FileInputStream fin=new FileInputStream("D:\\testout.txt");    
        BufferedInputStream bin=new BufferedInputStream(fin);    
        int i;    
        while((i=bin.read())!=-1){    
         System.out.print((char)i);    
        }    
        bin.close();    
        fin.close();    
      }catch(Exception e){System.out.println(e);}    
     }    
    }  

Here, we are assuming that you have following data in "testout.txt" file:

javaTpoint

Output:

javaTpoint

Java SequenceInputStream Class

Java SequenceInputStream class is used to read data from multiple streams. It reads data sequentially (one by one).

Java SequenceInputStream Class declaration

Let's see the declaration for Java.io.SequenceInputStream class:

Constructors of SequenceInputStream class

Constructor Description
SequenceInputStream(InputStream s1, InputStream s2) creates a new input stream by reading the data of two input stream in order, first s1 and then s2.
SequenceInputStream(Enumeration e) creates a new input stream by reading the data of an enumeration whose type is InputStream.

Methods of SequenceInputStream class

Method Description
int read() It is used to read the next byte of data from the input stream.
int read(byte[] ary, int off, int len) It is used to read len bytes of data from the input stream into the array of bytes.
int available() It is used to return the maximum number of byte that can be read from an input stream.
void close() It is used to close the input stream.

Java SequenceInputStream Example

In this example, we are printing the data of two files testin.txt and testout.txt.

    package com.javatpoint;  
      
    import java.io.*;  
    class InputStreamExample {    
      public static void main(String args[])throws Exception{    
       FileInputStream input1=new FileInputStream("D:\\testin.txt");    
       FileInputStream input2=new FileInputStream("D:\\testout.txt");    
       SequenceInputStream inst=new SequenceInputStream(input1, input2);    
       int j;    
       while((j=inst.read())!=-1){    
        System.out.print((char)j);    
       }    
       inst.close();    
       input1.close();    
       input2.close();    
      }    
    }    

Here, we are assuming that you have two files: testin.txt and testout.txt which have following information:

testin.txt:

Welcome to Java IO Programming.

testout.txt:

It is the example of Java SequenceInputStream class.

After executing the program, you will get following output:

Output:

Welcome to Java IO Programming. It is the example of Java SequenceInputStream class.

Example that reads the data from two files and writes into another file

In this example, we are writing the data of two files testin1.txt and testin2.txt into another file named testout.txt.

    package com.javatpoint;  
      
    import java.io.*;    
    class Input1{    
      public static void main(String args[])throws Exception{    
       FileInputStream fin1=new FileInputStream("D:\\testin1.txt");    
       FileInputStream fin2=new FileInputStream("D:\\testin2.txt");    
       FileOutputStream fout=new FileOutputStream("D:\\testout.txt");      
       SequenceInputStream sis=new SequenceInputStream(fin1,fin2);    
       int i;    
       while((i=sis.read())!=-1)    
       {    
         fout.write(i);        
       }    
       sis.close();    
       fout.close();      
       fin1.close();      
       fin2.close();       
       System.out.println("Success..");  
      }    
    }    

Output:

Succeess...

testout.txt:

    Welcome to Java IO Programming. It is the example of Java SequenceInputStream class.  

SequenceInputStream example that reads data using enumeration

If we need to read the data from more than two files, we need to use Enumeration. Enumeration object can be obtained by calling elements() method of the Vector class. Let's see the simple example where we are reading the data from 4 files: a.txt, b.txt, c.txt and d.txt.

    package com.javatpoint;  
    import java.io.*;    
    import java.util.*;    
    class Input2{    
    public static void main(String args[])throws IOException{    
    //creating the FileInputStream objects for all the files    
    FileInputStream fin=new FileInputStream("D:\\a.txt");    
    FileInputStream fin2=new FileInputStream("D:\\b.txt");    
    FileInputStream fin3=new FileInputStream("D:\\c.txt");    
    FileInputStream fin4=new FileInputStream("D:\\d.txt");    
    //creating Vector object to all the stream    
    Vector v=new Vector();    
    v.add(fin);    
    v.add(fin2);    
    v.add(fin3);    
    v.add(fin4);              
    //creating enumeration object by calling the elements method    
    Enumeration e=v.elements();      
    //passing the enumeration object in the constructor    
    SequenceInputStream bin=new SequenceInputStream(e);    
    int i=0;      
    while((i=bin.read())!=-1){    
    System.out.print((char)i);    
    }     
    bin.close();    
    fin.close();    
    fin2.close();    
    }    
    }    

The a.txt, b.txt, c.txt and d.txt have following information:

a.txt:

Welcome

b.txt:

to

c.txt:

java

d.txt:

programming

Output:

Welcometojavaprogramming

Java ByteArrayOutputStream Class

ava ByteArrayOutputStream class is used to write common data into multiple files. In this stream, the data is written into a byte array which can be written to multiple streams later.

The ByteArrayOutputStream holds a copy of data and forwards it to multiple streams. The buffer of ByteArrayOutputStream automatically grows according to data.

Java ByteArrayOutputStream class declaration

Let's see the declaration for Java.io.ByteArrayOutputStream class:

    public class ByteArrayOutputStream extends OutputStream  

Java ByteArrayOutputStream class constructors

Constructor Description
SequenceInputStream(InputStream s1, InputStream s2) creates a new input stream by reading the data of two input stream in order, first s1 and then s2.
SequenceInputStream(Enumeration e) creates a new input stream by reading the data of an enumeration whose type is InputStream.

Methods of SequenceInputStream class

Constructor Description
ByteArrayOutputStream() Creates a new byte array output stream with the initial capacity of 32 bytes, though its size increases if necessary.
ByteArrayOutputStream(int size) Creates a new byte array output stream, with a buffer capacity of the specified size, in bytes.

Java ByteArrayOutputStream class methods

Method Description
int size() It is used to returns the current size of a buffer.
byte[] toByteArray() It is used to create a newly allocated byte array.
String toString() It is used for converting the content into a string decoding bytes using a platform default character set.
String toString(String charsetName) It is used for converting the content into a string decoding bytes using a specified charsetName.
void write(int b) It is used for writing the byte specified to the byte array output stream.
void write(byte[] b, int off, int len It is used for writing len bytes from specified byte array starting from the offset off to the byte array output stream.
void writeTo(OutputStream out) It is used for writing the complete content of a byte array output stream to the specified output stream.
void reset() It is used to reset the count field of a byte array output stream to zero value.
void close() It is used to close the ByteArrayOutputStream.

Example of Java ByteArrayOutputStream

Let's see a simple example of java ByteArrayOutputStream class to write common data into 2 files: f1.txt and f2.txt.

    package com.javatpoint;  
    import java.io.*;  
    public class DataStreamExample {  
    public static void main(String args[])throws Exception{    
          FileOutputStream fout1=new FileOutputStream("D:\\f1.txt");    
          FileOutputStream fout2=new FileOutputStream("D:\\f2.txt");    
            
          ByteArrayOutputStream bout=new ByteArrayOutputStream();    
          bout.write(65);    
          bout.writeTo(fout1);    
          bout.writeTo(fout2);    
            
          bout.flush();    
          bout.close();//has no effect    
          System.out.println("Success...");    
         }    
        }   

Output:

Success...

f1.txt:

A

f2.txt:

A

Java ByteArrayInputStream Class

The ByteArrayInputStream is composed of two words: ByteArray and InputStream. As the name suggests, it can be used to read byte array as input stream.

Java ByteArrayInputStream class contains an internal buffer which is used to read byte array as stream. In this stream, the data is read from a byte array.

The buffer of ByteArrayInputStream automatically grows according to data.

Java ByteArrayInputStream class declaration

Let's see the declaration for Java.io.ByteArrayInputStream class:

    public class ByteArrayInputStream extends InputStream  

Java ByteArrayInputStream class constructors

Constructor Description
ByteArrayInputStream(byte[] ary) Creates a new byte array input stream which uses ary as its buffer array..
ByteArrayInputStream(byte[] ary, int offset, int len) Creates a new byte array input stream which uses ary as its buffer array that can read up to specified len bytes of data from an array.

Java ByteArrayInputStream class methods

Methods Description
int available() It is used to return the number of remaining bytes that can be read from the input stream.
int read() It is used to read the next byte of data from the input stream.
int read(byte[] ary, int off, int len) It is used to read up to len bytes of data from an array of bytes in the input stream.
boolean markSupported() It is used to test the input stream for mark and reset method.
long skip(long x) It is used to skip the x bytes of input from the input stream.
void mark(int readAheadLimit) It is used to set the current marked position in the stream.
void reset() It is used to reset the buffer of a byte array.
void close() It is used for closing a ByteArrayInputStream.

Example of Java ByteArrayInputStream

Let's see a simple example of java ByteArrayInputStream class to read byte array as input stream.

    package com.javatpoint;  
    import java.io.*;  
    public class ReadExample {  
      public static void main(String[] args) throws IOException {  
        byte[] buf = { 35, 36, 37, 38 };  
        // Create the new byte array input stream  
        ByteArrayInputStream byt = new ByteArrayInputStream(buf);  
        int k = 0;  
        while ((k = byt.read()) != -1) {  
          //Conversion of a byte into character  
          char ch = (char) k;  
          System.out.println("ASCII value of Character is:" + k + "; Special character is: " + ch);  
        }  
      }  
    }  

Output:

ASCII value of Character is:35; Special character is: #
ASCII value of Character is:36; Special character is: $
ASCII value of Character is:37; Special character is: %
ASCII value of Character is:38; Special character is: &

Java DataOutputStream Class

Java DataOutputStream class allows an application to write primitive Java data types to the output stream in a machine-independent way.

Java application generally uses the data output stream to write data that can later be read by a data input stream.

Java DataOutputStream class declaration

Let's see the declaration for java.io.DataOutputStream class:

    public class DataOutputStream extends FilterOutputStream implements DataOutput  

Java DataOutputStream class methods

Methods Description
int size() It is used to return the number of bytes written to the data output stream.
void write(int b) It is used to write the specified byte to the underlying output stream.
void write(byte[] b, int off, int len) It is used to write len bytes of data to the output stream.
void writeBoolean(boolean v) It is used to write Boolean to the output stream as a 1-byte value.
void writeChar(int v) It is used to write char to the output stream as a 2-byte value.
void writeChars(String s) It is used to write string to the output stream as a sequence of characters.
void writeByte(int v) It is used to write a byte to the output stream as a 1-byte value.
void writeInt(int v) It is used to write an int to the output stream
void writeShort(int v) It is used to write a short to the output stream.
void writeShort(int v) It is used to write a short to the output stream.
void writeLong(long v) It is used to write a long to the output stream.
void writeUTF(String str) It is used to write a string to the output stream using UTF-8 encoding in portable manner.
void flush() It is used to flushes the data output stream.

Example of DataOutputStream class

In this example, we are writing the data to a text file testout.txt using DataOutputStream class.

    package com.javatpoint;  
      
    import java.io.*;  
    public class OutputExample {  
        public static void main(String[] args) throws IOException {  
            FileOutputStream file = new FileOutputStream(D:\\testout.txt);  
            DataOutputStream data = new DataOutputStream(file);  
            data.writeInt(65);  
            data.flush();  
            data.close();  
            System.out.println("Succcess...");  
        }  
    }  

Output:

Succcess...

testout.txt:

A

Java DataInputStream Class

Java DataInputStream class allows an application to read primitive data from the input stream in a machine-independent way.

Java application generally uses the data output stream to write data that can later be read by a data input stream.

Java DataInputStream class declaration

Let's see the declaration for java.io.DataInputStream class:

    public class DataInputStream extends FilterInputStream implements DataInput  
Methods Description
int read(byte[] b) It is used to read the number of bytes from the input stream.
int read(byte[] b, int off, int len) It is used to read len bytes of data from the input stream.
int readInt() It is used to read input bytes and return an int value..
byte readByte() It is used to read and return the one input byte.
char readChar() It is used to read two input bytes and returns a char value.
double readDouble() It is used to read eight input bytes and returns a double value.
boolean readBoolean() It is used to read one input byte and return true if byte is non zero, false if byte is zero.
int skipBytes(int x) It is used to skip over x bytes of data from the input stream.
String readUTF() It is used to read a string that has been encoded using the UTF-8 format.
void readFully(byte[] b) It is used to read bytes from the input stream and store them into the buffer array.
void readFully(byte[] b, int off, int len) It is used to read len bytes from the input stream.

Example of DataInputStream class

In this example, we are reading the data from the file testout.txt file.

    package com.javatpoint;  
    import java.io.*;    
    public class DataStreamExample {  
      public static void main(String[] args) throws IOException {  
        InputStream input = new FileInputStream("D:\\testout.txt");  
        DataInputStream inst = new DataInputStream(input);  
        int count = input.available();  
        byte[] ary = new byte[count];  
        inst.read(ary);  
        for (byte bt : ary) {  
          char k = (char) bt;  
          System.out.print(k+"-");  
        }  
      }  
    }  

Here, we are assuming that you have following data in "testout.txt" file:

JAVA

Output:

J-A-V-A

Java FilterOutputStream Class

Java FilterOutputStream class implements the OutputStream class. It provides different sub classes such as BufferedOutputStream and DataOutputStream to provide additional functionality. So it is less used individually.

Java FilterOutputStream class declaration

Let's see the declaration for java.io.FilterOutputStream class:

public class FilterOutputStream extends OutputStream 

Java FilterOutputStream class Methods

Methods Description
void write(int b) It is used to write the specified byte to the output stream.
void write(byte[] ary) It is used to write ary.length byte to the output stream.
void write(byte[] b, int off, int len) It is used to write len bytes from the offset off to the output stream.
void flush() It is used to flushes the output stream.
void close() It is used to close the output stream.

Example of FilterOutputStream class

    import java.io.*;  
    public class FilterExample {  
        public static void main(String[] args) throws IOException {  
            File data = new File("D:\\testout.txt");  
            FileOutputStream file = new FileOutputStream(data);  
            FilterOutputStream filter = new FilterOutputStream(file);  
            String s="Welcome to javaTpoint.";      
            byte b[]=s.getBytes();      
            filter.write(b);     
            filter.flush();  
            filter.close();  
            file.close();  
            System.out.println("Success...");  
        }  
    }  
       

Output:

Success...

testout.txt

Welcome to javaTpoint.

Java FilterInputStream Class

Java FilterInputStream class implements the InputStream. It contains different sub classes as BufferedInputStream, DataInputStream for providing additional functionality. So it is less used individually.

Java FilterInputStream class declaration

Let's see the declaration for java.io.FilterInputStream class

    public class FilterInputStream extends InputStream  

Java FilterInputStream class Methods

Methods Description
int available() It is used to return an estimate number of bytes that can be read from the input stream.
int read() It is used to read the next byte of data from the input stream.
int read(byte[] b) It is used to read up to byte.length bytes of data from the input stream.
long skip(long n) It is used to skip over and discards n bytes of data from the input stream..
boolean markSupported() It is used to test if the input stream support mark and reset method.
void mark(int readlimit) It is used to mark the current position in the input stream.
void reset() It is used to reset the input stream..
void close()) It is used to close the input stream.

Example of FilterInputStream class

    import java.io.*;  
    public class FilterExample {  
        public static void main(String[] args) throws IOException {  
            File data = new File("D:\\testout.txt");  
            FileInputStream  file = new FileInputStream(data);  
            FilterInputStream filter = new BufferedInputStream(file);  
            int k =0;  
            while((k=filter.read())!=-1){  
                System.out.print((char)k);  
            }  
            file.close();  
            filter.close();  
        }  
    }  

Here, we are assuming that you have following data in "testout.txt" file:

Welcome to javatpoint

Output:

Welcome to javatpoint

Java - ObjectStreamClass

ObjectStreamClass act as a Serialization descriptor for class. This class contains the name and serialVersionUID of the class.

Fields

Modifier and Type Field Description
static ObjectStreamField[] NO_FIELDS serialPersistentFields value indicating no serializable fields
static ObjectStreamField[] NO_FIELDS serialPersistentFields value indicating no serializable fields

Method

Modifier and Type Method Description
Class <?> forClass() It returns the class in the local VM that this version is mapped to.
ObjectStreamField getField(String name) It gets the field of this class by name.
ObjectStreamField[] getFields() It returns an array of the fields of this serialization class.
String getName() It returns the name of the class described by this descriptor.
long getSerialVersionUID() It returns the serialVersionUID for this class.
Static ObjectStreamClass lookup(Class<?> cl) It finds the descriptor for a class that can be serialized.
Static ObjectStreamClass lookupAny(Class<?> cl) It returns the descriptor for any class, regardless of whether it implements Serializable.
String toString() It returns a string describing this ObjectStreamClass.

Example

    import java.io.ObjectStreamClass;  
    import java.util.Calendar;  
      
    public class ObjectStreamClassExample {  
        public static void main(String[] args) {  
      
            // create a new object stream class for Integers  
            ObjectStreamClass osc = ObjectStreamClass.lookup(SmartPhone.class);  
      
            // get the value field from ObjectStreamClass for integers  
            System.out.println("" + osc.getField("price"));  
      
            // create a new object stream class for Calendar  
            ObjectStreamClass osc2 = ObjectStreamClass.lookup(String.class);  
      
            // get the Class instance for osc2  
            System.out.println("" + osc2.getField("hash"));  
      
        }  
    }  

Output:

I price
null

Java ObjectStreamField class

A description of a Serializable field from a Serializable class. An array of ObjectStreamFields is used to declare the Serializable fields of a class.

The java.io.ObjectStreamClass.getField(String name) method gets the field of this class by name.

Constructor

Constructor Description
ObjectStreamField(String name, Class<?> type)It creates a Serializable field with the specified type.
ObjectStreamField(String name, Class<?> type, boolean unshared) It creates an ObjectStreamField representing a serializable field with the given name and type.

Methods

Modifier and Type Method Description
int compareTo(Object obj) It compares this field with another ObjectStreamField.
String getName() It gets the name of this field.
int GetOffset() Offset of field within instance data.
Class<?> getType() It get the type of the field.
char getTypeCode() It returns character encoding of field type.
String getTypeString() It return the JVM type signature..
boolean isPrimitive()) It return true if this field has a primitive type.
boolean isUnshared() It returns boolean value indicating whether or not the serializable field represented by this ObjectStreamField instance is unshared.
protected void setOffset(int offset) Offset within instance data.
String toString() It return a string that describes this field.

public char getTypeCode()

Returns character encoding of field type. The encoding is as follows:

B byte
C char
D double
F float
I int
J long
L class or interface
S short
Z boolean
[ array

Returns:the typecode of the serializable field

Example:

    import java.io.ObjectStreamClass;  
    import java.util.Calendar;  
      
    public class ObjectStreamClassExample {  
         public static void main(String[] args) {  
                 
              // create a new object stream class for Integers  
              ObjectStreamClass osc = ObjectStreamClass.lookup(String.class);  
      
              // get the value field from ObjectStreamClass for integers  
              System.out.println("" + osc.getField("value"));  
      
              // create a new object stream class for Calendar  
              ObjectStreamClass osc2 = ObjectStreamClass.lookup(Calendar.class);  
      
              // get the Class instance for osc2  
              System.out.println("" + osc2.getField("isTimeSet"));  
      
           }  
    }  

Output:

I value
Z isTimeSet

Java Console Class

The Java Console class is be used to get input from console. It provides methods to read texts and passwords.

If you read password using Console class, it will not be displayed to the user.

The java.io.Console class is attached with system console internally. The Console class is introduced since 1.5.

Let's see a simple example to read text from console.

    String text=System.console().readLine();    
    System.out.println("Text is: "+text);    

Java Console class declaration

Let's see the declaration for Java.io.Console class:

    public final class Console extends Object implements Flushable  

Java Console class methods

Method Description
Reader reader() It is used to retrieve the reader object associated with the console
String readLine() It is used to read a single line of text from the console.
String readLine(String fmt, Object... args) It provides a formatted prompt then reads the single line of text from the console.
char[] readPassword() It is used to read password that is not being displayed on the console.
char[] readPassword(String fmt, Object... args) It provides a formatted prompt then reads the password that is not being displayed on the console.
Console format(String fmt, Object... args) It is used to write a formatted string to the console output stream.
Console printf(String format, Object... args) It is used to write a string to the console output stream.
PrintWriter writer() It is used to retrieve the PrintWriter object associated with the console.
void flush() It is used to flushes the console.

How to get the object of Console

System class provides a static method console() that returns the singleton instance of Console class.

    public static Console console(){}   

Let's see the code to get the instance of Console class.

Console c=System.console();  

Java Console Example

    import java.io.Console;  
    class ReadStringTest{    
    public static void main(String args[]){    
    Console c=System.console();    
    System.out.println("Enter your name: ");    
    String n=c.readLine();    
    System.out.println("Welcome "+n);    
    }    
    }  

Output

Enter your name: Nakul Jain
Welcome Nakul Jain

Java Console Example to read password

    import java.io.Console;  
    class ReadPasswordTest{    
    public static void main(String args[]){    
    Console c=System.console();    
    System.out.println("Enter password: ");    
    char[] ch=c.readPassword();    
    String pass=String.valueOf(ch);//converting char array into string    
    System.out.println("Password is: "+pass);    
    }    
    }  

Output

Enter password: 
Password is: 123

Java FilePermission Class

Java FilePermission class contains the permission related to a directory or file. All the permissions are related with path. The path can be of two types:

1) D:\\IO\\-: It indicates that the permission is associated with all sub directories and files recursively.

2) D:\\IO\\*: It indicates that the permission is associated with all directory and files within this directory excluding sub directories

Java FilePermission class declaration

Let's see the declaration for Java.io.FilePermission class:

public final class FilePermission extends Permission implements Serializable 

Methods of FilePermission class

Method Description
ByteArrayOutputStream() Creates a new byte array output stream with the initial capacity of 32 bytes, though its size increases if necessary.
ByteArrayOutputStream(int size) Creates a new byte array output stream, with a buffer capacity of the specified size, in bytes.

Java FilePermission class methods

Method Description
int hashCode() It is used to return the hash code value of an object.
String getActions() It is used to return the "canonical string representation" of an action.
boolean equals(Object obj) It is used to check the two FilePermission objects for equality.
boolean implies(Permission p) It is used to check the FilePermission object for the specified permission.
PermissionCollection newPermissionCollection() It is used to return the new PermissonCollection object for storing the FilePermission object.

Java FilePermission Example

Let's see the simple example in which permission of a directory path is granted with read permission and a file of this directory is granted for write permission.

    package com.javatpoint;  
      
    import java.io.*;  
    import java.security.PermissionCollection;  
    public class FilePermissionExample{  
           public static void main(String[] args) throws IOException {  
            String srg = "D:\\IO Package\\java.txt";  
            FilePermission file1 = new FilePermission("D:\\IO Package\\-", "read");  
            PermissionCollection permission = file1.newPermissionCollection();  
            permission.add(file1);  
                 FilePermission file2 = new FilePermission(srg, "write");  
                 permission.add(file2);  
                 if(permission.implies(new FilePermission(srg, "read,write"))) {  
                 System.out.println("Read, Write permission is granted for the path "+srg );  
                 }else {  
                System.out.println("No Read, Write permission is granted for the path "+srg);            }  
           }   
    }  

Output

Read, Write permission is granted for the path D:\IO Package\java.txt

Java Writer

It is an abstract class for writing to character streams. The methods that a subclass must implement are write(char[], int, int), flush(), and close(). Most subclasses will override some of the methods defined here to provide higher efficiency, functionality or both.

Fields

Modifier and Type Field Description
protected Object lock The object used to synchronize operations on this stream.

Constructor

Modifier Constructor Description
protected Writer() It creates a new character-stream writer whose critical sections will synchronize on the writer itself.
protected Writer(Object lock) It creates a new character-stream writer whose critical sections will synchronize on the given object.

Methods

Modifier and Type Method Description
Writer append(char c) It appends the specified character to this writer.
Writer append(CharSequence csq) It appends the specified character sequence to this writer
Writer append(CharSequence csq, int start, int end) It appends a subsequence of the specified character sequence to this writer.
abstract void close() It closes the stream, flushing it first.
abstract void flush() It flushes the stream.
void write(char[] cbuf) It writes an array of characters.
abstract void write(char[] cbuf, int off, int len) It writes a portion of an array of characters.
void write(int c) It writes a single character.
void write(String str) It writes a string.
void write(String str, int off, int len) It writes a portion of a string.

Java Writer Example

    import java.io.*;  
    public class WriterExample {  
        public static void main(String[] args) {  
            try {  
                Writer w = new FileWriter("output.txt");  
                String content = "I love my country";  
                w.write(content);  
                w.close();  
                System.out.println("Done");  
            } catch (IOException e) {  
                e.printStackTrace();  
            }  
        }  
    }  

Output:

Done

output.txt:

I love my country

bONEandALL
Visitor

Total : 26654

Today :3

Today Visit Country :

  • France
  • United States