Files

  • Whenever we need to store data permanently then we use the concept of files.
  • We can read data from an existing file. We can create a file and write data into it. We can copy the contents of one file to another file, e. t. c... To perform all these operations, we use input/output streams.
  • Some of the classes using which we can operate on files are file input stream and File Output Stream, File Readers and File Writers e. t. c….
  • File input stream and File Output Stream classes come under byte oriented classes and File Reader and File Writer come under character oriented classes.
  • Object of File Input Stream class contains address of the file from which we need to read the data.
  • Similarly, object of File output stream class contains address of the file to which we need to write the data.

Example program:

Write a program to read data from the keyword and write this data into a file named file1.txt.

Import java.io.*;

Class Filedemo1

{

Public static void main (string args [ ])

{

Try

{

Buffered Reader br = new Buffered Reader (new Input stream Reader (system. in));

System. Out. Prinln(“enter the data : ”);

String s1 = br. readline ();

// file output stream fos = new fileoutput stream (“file1.txt”);

File output stream fos = new fileoutput stream (“file1.txt”, true);

// FOS. Write ();

S1. Get Bytes ();

fOS. Write (ba);

fos .close ();

}

Catch (Exception e)

{

System. Out. Prinln(e);

}

}

}

Explanation:

  • Object of File output stream class contains the address of file.txt. If the file does not exist, then the file is created with the given name and then its address will be assigned to fos.
  • Remember that whenever we open a file in read/ write mode, the file pointer always points to the location.
  • In this example we are writing data into the file. For the first time when we open the file and write the data we don’t have any problem. But when we open the file for the second time and write the data, the existing data will be over written because, whenever the file is opened, the file pointer points to the zero’s location. So it is our duty, to bring the file pointer to the end of file before writing data in it.