1. Introduction to File Handling
Whenever we run Java program, it is executed in RAM and hence once
we close Java and reopen it, the data i.e. the output is not saved. Till
now we have used variables and arrays to store the data but:
a. The data is lost when a variable goes out of scope or when the
program is terminated.
b. It is difficult to handle large amount of data using variables and
arrays.
Hence, to overcome this issue we use secondary storage devices
like floppy disk, hard disk to store data permanently. In secondary
storage devices the data is stored in the format of files. Storing and
managing data using files is known as file processing or file
handling.
File Handling is an integral part of any programming language as file
handling enables us to store the output of any particular program in a
file and allows us to perform certain operations on it.
In simple words, file handling means reading and writing data to a file.
2. Concept of Stream:
In File Handling, input refers to the flow of data into a program and
output means the flow of data out of a program. Input to a program
may come from Keyboard, mouse, memory, disk or from an another
program. Similarly, output from a program may go the screen,
printer, memory, disk or to an another program.
3. Introduction to File Handling:
Stream in Java is a path along which data flows. It has a source and a
destination. A stream presents a uniform, easy-to-use, object-
oriented interface between the program and the input/output
devices.
There are two major concepts:
a. Read from file -> Input Stream
b. Write to file -> Output Stream
4. 1. Input Stream:
The Java InputStream class is the superclass of all input streams. The input
stream is used to read data from numerous input devices like the keyboard,
network, etc. InputStream is an abstract class, and because of this, it is not
useful by itself. However, its subclasses are used to read data.
There are several subclasses of the InputStream class, which are as follows:
1.AudioInputStream
2.ByteArrayInputStream
3.FileInputStream
4.FilterInputStream
5.StringBufferInputStream
6.ObjectInputStream
Creating an InputStream
InputStream obj = new FileInputStream();
5. 2. Output Stream:
The output stream is used to write data to numerous output devices
like the monitor, file, etc. OutputStream is an abstract superclass
that represents an output stream. OutputStream is an abstract
class and because of this, it is not useful by itself. However, its
subclasses are used to write data.
There are several subclasses of the OutputStream class which are
as follows:
1.ByteArrayOutputStream
2.FileOutputStream
3.StringBufferOutputStream
4.ObjectOutputStream
5.DataOutputStream
6.PrintStream
Creating an OutputStream
OutputStream obj = new FileOutputStream();
6. Stream Classes
The java.io package contains a large number of stream classes
that provide capabilities for processing all types of data. The following
classification shows the concept of stream classes in Java.
7. Create a File:
To create a file in Java, we use the createNewFile() method.
This method returns a boolean value: "true" if the file was
successfully created, and "false" if the file already exists. Note that
the method is enclosed in a try...catch block. This is necessary
because it throws an IOExcetion if an error occurs (if the file cannot
be created for some reason).
When we use createNewFile() method and provide only the
filename, the file is created in the same directory where we have
saved the program.
To create a file in a specific directory (requires permission), specify
the path of the file and use double backslashes to escape the ""
character (for Windows). On Mac and Linux you can just write the
path, like: /Users/name/filename.txt
8. import java.io.File;
import java.io.IOException;
public class filehandcreate
{
public static void main(String[] args)
{
try
{
File f1=new File("file1.txt");
if(f1.createNewFile())
{
System.out.println("file created "+ f1.getName());
}
else
{
System.out.println("file already exists.");
}
}
catch(IOException e)
{
System.out.println(e);
e.printStackTrace(); // it returns where the exception is occurred
}
}
}
9. Creating file at desired location
import java.io.File;
import java.io.IOException;
public class CreateFileex1 {
public static void main(String[] args) {
try {
File f1=new File("F:JAVAjava pptsahil.txt");
if(f1.createNewFile())
{
System.out.println("file created sucessfully");
}
else
{
System.out.println("file already exits ");
}
}
catch(IOException e)
{
System.out.println(e);
}
}
}
10. Write To a File:
Let's move further and in the following example, we
use the FileWriter class together with its write() method to
write some text to the file we created in the example
above. Note that when you are done writing to the file, you
should close it with the close() method.
Read a File
you learned how to create and write to a file.
In the following example, we use the Scanner class to
read the contents of the text file we created in the
previous chapter:
11. import java.io.IOException;
public class fileex1{
public static void main(String[] args) {
File myFile = new File(“exfile1.txt");
try {
FileWriter fW = new FileWriter(“exfile1.txt");
fW.write(“hello everyone !how are you");
fW.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
12. Using Reader class
import java.io.*;
public class readfileex1 {
public static void main(String[] args) {
char a[]=new char[10000];
try {
FileReader fr=new FileReader("C:UsersSUREBITeclipse-workspaceAshwini.txt");
fr.read(a);
System.out.println(a);
fr.close();
}
catch(IOException e)
{
System.out.println(e);
}
}
}
13. import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class fileex2 {
public static void main(String[] args) {
File myFile = new File("exfile1.txt");
try {
Scanner sc = new Scanner(myFile);
while(sc.hasNextLine()){
String line = sc.nextLine();
System.out.println(line);
}
sc.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
15. import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class fileex3{
public static void main(String[] args) {
File myFile = new File(“exfile1.txt");
if(myFile.delete()){
System.out.println("I have deleted: " + myFile.getName());
}
else{
System.out.println("Some problem occurred while deleting the file");
}
}
}
16. Methods
1) getName(): it returns the name of the file
ex: String a =f1. getName():
2) getAbsolutePath() : it returns the complete path or location of file
ex. System.out.println(f1. getAbsolutePath());
3) exists(): it returns the boolean value , true if the file is already
created.
boolean a =f1. exists();
4) canWrite(): it returns the boolean value , true if we can write into
file
boolean a =f1. canWrite();
5) canRead(): it returns the boolean value , true if we can read the
file
boolean a =f1. canWrite();
6) length():it returns the size of the file in byte
Int a=f1.length();
17. import java.io.File; // Import the File class
public class getinfo
{
public static void main(String[] args)
{
File myObj = new File("file1.txt");
if (myObj.exists())
{
System.out.println("File name: " + myObj.getName());
System.out.println("Absolute path: " + myObj.getAbsolutePath());
System.out.println("Writeable: " + myObj.canWrite());
System.out.println("Readable " + myObj.canRead());
System.out.println("File size in bytes " + myObj.length());
}
else
{
System.out.println("The file does not exist.");
}
}
}