File Handling in Java
A file is a named location that can be used to store related information. For
example,main.java is a Java file that contains information about the Java program.
A directory is a collection of files and subdirectories. A directory inside a directory is
known as subdirectory.There are several File Operations like creating a new File,
getting information about File, writing into a File, reading from a
File and deleting a File. File operations, it is required that we should have knowledge
of Stream and File methods
In Java, with the help of File Class, we can work with files. This File Class is
inside the java.io package. The File class can be used by creating an object of
the class and then specifying the name of the file.Streams in Java
In Java, a sequence of data is known as a stream.
This concept is used to perform I/O operations on a file.
There are two types of streams :
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
// Creating an InputStream
InputStream obj = new FileInputStream();
Here, an input stream is created using FileInputStream.
Note: We can create an input stream from other subclasses as well as
InputStream.
Methods of InputStream
S Method Description
No.
1 read() Reads one byte of data from the input stream.
S Method Description
No.
read(byte[] array) Reads byte from the stream and stores that byte in the
2
() specified array.
It marks the position in the input stream until the data
3 mark()
has been read.
Returns the number of bytes available in the input
4 available()
stream.
It checks if the mark() method and the reset() method is
5 markSupported()
supported in the stream.
Returns the control to the point where the mark was set
6 reset()
inside the stream.
Skips and removes a particular number of bytes from
7 skips()
the input stream.
8 close() Closes the input stream.
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
// Creating an OutputStream
OutputStream obj = new FileOutputStream();
Here, an output stream is created using FileOutputStream.
Note: We can create an output stream from other subclasses as well
as OutputStream.
Methods of OutputStream
S. Method Description
No.
1. write() Writes the specified byte to the output stream.
write(byte[] Writes the bytes which are inside a specific array to the
2.
array) output stream.
3. close() Closes the output stream.
Forces to write all the data present in an output stream to
4. flush()
the destination.
Based on the data type, there are two types of streams :
Byte Stream
Byte Stream is mainly involved with byte data. A file handling process with a byte
stream is a process in which an input is provided and executed with the byte data.
Byte Input Stream: Used to read byte data from different devices.
Byte Output Stream: Used to write byte data to different devices.
Character Stream
Character Stream is mainly involved with character data. A file handling process
with a character stream is a process in which an input is provided and executed with
the character data.
Character Input Stream: Used to read character data from different devices.
Character Output Stream: Used to write character data to different devices.
ava File Class Methods
The following table depicts several File Class methods:
Method Name Description Return Type
canRead() It tests whether the file is readable or not. Boolean
canWrite() It tests whether the file is writable or not. Boolean
Method Name Description Return Type
createNewFile(
It creates an empty file. Boolean
)
delete() It deletes a file. Boolean
exists() It tests whether the file exists or not. Boolean
length() Returns the size of the file in bytes. Long
getName() Returns the name of the file. String
list() Returns an array of the files in the directory. String[]
mkdir() Creates a new directory. Boolean
1. Create a File
In order to create a file in Java, you can use the createNewFile() method.
If the file is successfully created, it will return a Boolean value true and false if
the file already exists.
// Import the File class
import java.io.File;
// Import the IOException class to handle errors
import java.io.IOException;
public class GFG {
public static void main(String[] args)
{
try {
File Obj = new File("myfile.txt");
if (Obj.createNewFile()) {
System.out.println("File created: "
+ Obj.getName());
}
else {
System.out.println("File already exists.");
}
}
catch (IOException e) {
System.out.println("An error has occurred.");
e.printStackTrace();
}
}
}
Read from a File: We will use the Scanner class in order to read contents from a
file. Following is a demonstration of how to read contents from a file in Java :
// Import the File class
import java.io.File;
// Import this class for handling errors
import java.io.FileNotFoundException;
// Import the Scanner class to read content from text files
import java.util.Scanner;
public class GFG {
public static void main(String[] args)
{
try {
File Obj = new File("myfile.txt");
Scanner Reader = new Scanner(Obj);
while (Reader.hasNextLine()) {
String data = Reader.nextLine();
System.out.println(data);
}
Reader.close();
}
catch (FileNotFoundException e) {
System.out.println("An error has occurred.");
e.printStackTrace();
}
}
}
3. Write to a File: We use the FileWriter class along with its write() method in
order to write some text to the file. Following is a demonstration of how to write
text to a file in Java :
// Import the FileWriter class
import java.io.FileWriter;
// Import the IOException class for handling errors
import java.io.IOException;
public class GFG {
public static void main(String[] args)
{
try {
FileWriter Writer
= new FileWriter("myfile.txt");
Writer.write(
"Files in Java are seriously good!!");
Writer.close();
System.out.println("Successfully written.");
}
catch (IOException e) {
System.out.println("An error has occurred.");
e.printStackTrace();
}
}
}
4. Delete a File: We use the delete() method in order to delete a file. Following is a
demonstration of how to delete a file in Java :
// Import the File class
import java.io.File;
public class GFG {
public static void main(String[] args)
{
File Obj = new File("myfile.txt");
if (Obj.delete()) {
System.out.println("The deleted file is : "
+ Obj.getName());
}
else {
System.out.println(
"Failed in deleting the file.");
}
}
}
File Permissions in Java
Java provides a number of method calls to check and change the permission of a
file, such as a read-only file can be changed to have permissions to write. File
permissions are required to be changed when the user wants to restrict the
operations permissible on a file.
Method Action Performed
Returns true if and only if the abstract pathname exists and the
canExecutable()
application is allowed to execute the file
Tests whether the application can read the file denoted by this
canRead()
abstract pathname
Returns true if and only if the file system actually contains a file
canWrite() denoted by this abstract pathname and the application is allowed
to write to the file; false otherwise
// Java Program to Check the Current File Permissions
// Importing required classes
import java.io.*;
// Main class
public class Test {
// Main driver method
public static void main(String[] args)
{
// Creating a file by
// creating object of File class
File file
= new File("C:\\Users\\Mayank\\Desktop\\1.txt");
// Checking if the file exists
// using exists() method of File class
boolean exists = file.exists();
if (exists == true) {
// Printing the permissions associated
// with the file
System.out.println("Executable: "
+ file.canExecute());
System.out.println("Readable: "
+ file.canRead());
System.out.println("Writable: "
+ file.canWrite());
}
// If we enter else it means
// file does not exists
else {
System.out.println("File not found.");
}
}
}
// Java Program Illustrating Copying a src File
// to Destination
// Importing required classes
import java.io.*;
// Main class
// src2dest
class GFG {
// Main driver method
public static void main(String args[])
throws FileNotFoundException, IOException
{
// If file doesnot exist FileInputStream throws
// FileNotFoundException and read() write() throws
// IOException if I/O error occurs
FileInputStream fis = new FileInputStream(args[0]);
// Assuming that the file exists and
// need not to be checked
FileOutputStream fos
= new FileOutputStream(args[1]);
int b;
while ((b = fis.read()) != -1)
fos.write(b);
// read() method will read only next int so we used
// while loop here in order to read upto end of file
// and keep writing the read int into dest file
fis.close();
fos.close();
}
}