enfrptes

sendassignment@tutorspoint.com

Files Java Homework Help

What are Files in Java?

a) Whenever we need to store data permanently then we use the concept of files.

b) 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.

c) 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….

d) File input stream and File Output Stream classes come under byte-oriented classes and File Reader and File Writer come under character-oriented classes.

e) The object of the File Input Stream class contains the address of the file from which we need to read the data.

f) Similarly, an object of the File output stream class contains the 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 file output stream (“file1.txt”);

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

// FOS. Write ();

S1. Get Bytes ();

fOS. Write (ba);

fos .close ();

}

Catch (Exception e)

{

System. Out. Prinn(e);

}

}

}

Explanation:

a) The object of the 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.

b) Remember that whenever we open a file in reading/ write mode, the file pointer always points to the location.

c) 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 overwritten 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 the file before writing data in it.