Reading and writing files


1Reading and writing files:

As discussed earlier, a stream can be classified as a series of data. To read data InputStream is used from a source as well as for writing data the outputStream is used.
Here comes the hierarchy of classes that we have to deal with Output and Input Streams.

You know about the most common used streams and that are FileoutStream and Inputstream, which would be defined in this tutorial.

Types of constructors available:

Following constructor takes a filename like a string to create an input stream object to read the file −

InputStream f = new FileInputStream(“C:/java/hello”);
Following constructor takes a file object to create an inputstream object in order to read the file. First we have to create a file object by using File() method as follows −

File f = new File(“C:/java/hello”);

InputStream f = new FileInputStream(f);

Once you got InputStream object in your hand, then there is a series of things of helper methods which can also be used to read stream or to do other operations on that stream.

Method & Description

  1. public void close() throws IOException{}This way shut downs the file output stream. Releases any system resources associated with the file. Throws an IOException.
  2. protected void finalize()throws IOException {}This method cleans up the connection to the file. It Makes sure that the close method of this file output stream is known when there no more references to this stream. Throws an IOException.
  3. public void write(int w)throws IOException{}This methods writes the specified byte to the output stream.
  4. public void write(byte[] w)Writes w.length bytes from the mentioned byte array to the OutputStream.