0% found this document useful (0 votes)
8 views24 pages

File

The document provides an overview of file handling in Java, detailing various file operations such as creating, reading, writing, and deleting files. It introduces key concepts like streams, differentiating between byte and character streams, and lists essential methods of the Java File class. Additionally, it includes code examples for each file operation to illustrate practical usage.

Uploaded by

Ashok Garg
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views24 pages

File

The document provides an overview of file handling in Java, detailing various file operations such as creating, reading, writing, and deleting files. It introduces key concepts like streams, differentiating between byte and character streams, and lists essential methods of the Java File class. Additionally, it includes code examples for each file operation to illustrate practical usage.

Uploaded by

Ashok Garg
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 24

File Handling

File Operations in Java


In Java, a File is an abstract data type. A named location used to store related information is
known as a File. 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.

Before understanding the File operations, it is required that we should have knowledge
of Stream and File methods. If you have knowledge about both of them, you can skip it.
Stream
A series of data is referred to as a stream. In Java

, Stream is classified into two types, i.e., Byte Stream and Character Stream.

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.

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.

To get more knowledge about the stream, click here


Java File Class Methods
S.No Method Return Description
. Type
1. canRead() Boolean The canRead() method is used to check whether we can
read the data of the file or not.

2. createNewFile() Boolean The createNewFile() method is used to create a new


empty file.

3. canWrite() Boolean The canWrite() method is used to check whether we can


write the data into the file or not.

4. exists() Boolean The exists() method is used to check whether the specified
file is present or not.

5. delete() Boolean The delete() method is used to delete a file.

6. getName() String The getName() method is used to find the file name.

7. getAbsolutePat String The getAbsolutePath() method is used to get the absolute


h() pathname of the file.

8. length() Long The length() method is used to get the size of the file in
bytes.

9. list() String[] The list() method is used to get an array of the files
available in the directory.

10. mkdir() Boolean The mkdir() method is used for creating a new directory.
File Operations
We can perform the following operation on a file:

o Create a File
o Get File Information
o Write to a File
o Read from a File
o Delete a File
Create a File
Create a File operation is performed to create a new file. We use
the createNewFile() method of file. The createNewFile() method returns true when it
successfully creates a new file and returns false when the file already exists.

Let's take an example of creating a file to understand how we can use


the createNewFile() method to perform this operation.

CreateFile.java

1. // Importing File class


2. import java.io.File;
3. // Importing the IOException class for handling errors
4. import java.io.IOException;
5. class CreateFile {
6. public static void main(String args[]) {
7. try {
8. // Creating an object of a file
9. File f0 = new File("D:FileOperationExample.txt");
10. if (f0.createNewFile()) {
11. System.out.println("File " + f0.getName() + " is created successfully.");
12. } else {
13. System.out.println("File is already exist in the directory.");
14. }
15. } catch (IOException exception) {
16. System.out.println("An unexpected error is occurred.");
17. exception.printStackTrace();
18. }
19. }
20.}

Output:

Explanation:

In the above code, we import the File and IOException class for performing file operation and
handling errors, respectively. We create the f0 object of the File class and specify the
location of the directory where we want to create a file. In the try block, we call
the createNewFile() method through the f0 object to create a new file in the specified
location. If the method returns false, it will jump to the else section. If there is any error, it
gets handled in the catch block.

Get File Information


The operation is performed to get the file information. We use several methods to get the
information about the file like name, absolute path, is readable, is writable and length.

Let's take an example to understand how to use file methods to get the information of the
file.

FileInfo.java

1. // Import the File class


2. import java.io.File;
3. class FileInfo {
4. public static void main(String[] args) {
5. // Creating file object
6. File f0 = new File("D:FileOperationExample.txt");
7. if (f0.exists()) {
8. // Getting file name
9. System.out.println("The name of the file is: " + f0.getName());
10.
11. // Getting path of the file
12. System.out.println("The absolute path of the file is: " + f0.getAbsolutePath());
13.
14. // Checking whether the file is writable or not
15. System.out.println("Is file writeable?: " + f0.canWrite());
16.
17. // Checking whether the file is readable or not
18. System.out.println("Is file readable " + f0.canRead());
19.
20. // Getting the length of the file in bytes
21. System.out.println("The size of the file in bytes is: " + f0.length());
22. } else {
23. System.out.println("The file does not exist.");
24. }
25. }
26.}

Output:
Description:

In the above code, we import the java.io.File package and create a class FileInfo. In the
main method, we create an object of the text file which we have created in our previous
example. We check the existence of the file using a conditional statement, and if it is
present, we get the following information about that file:

1. We get the name of the file using the getName()


2. We get the absolute path of the file using the getAbsolutePath() method of the file.
3. We check whether we can write data into a file or not using the canWrite()
4. We check whether we can read the data of the file or not using the canRead()
5. We get the length of the file by using the length()

If the file doesn't exist, we show a custom message.


Write to a File
The next operation which we can perform on a file is "writing into a file". In order to write
data into a file, we will use the FileWriter class and its write() method together. We need
to close the stream using the close() method to retrieve the allocated resources.

Let's take an example to understand how we can write data into a file.

WriteToFile.java

1. // Importing the FileWriter class


2. import java.io.FileWriter;
3.
4. // Importing the IOException class for handling errors
5. import java.io.IOException;
6.
7. class WriteToFile {
8. public static void main(String[] args) {
9.
10. try {
11. FileWriter fwrite = new FileWriter("D:FileOperationExample.txt");
12. // writing the content into the FileOperationExample.txt file
13. fwrite.write("A named location used to store related information is referred to as a File.");
14.
15. // Closing the stream
16. fwrite.close();
17. System.out.println("Content is successfully wrote to the file.");
18. } catch (IOException e) {
19. System.out.println("Unexpected error occurred");
20. e.printStackTrace();
21. }
22. }
23.}

Output:
Explanation:

In the above code, we import the java.io.FileWriter and java.io.IOException classes. We


create a class WriteToFile, and in its main method, we use the try-catch block. In the try
section, we create an instance of the FileWriter class, i.e., fwrite. We call the write method
of the FileWriter class and pass the content to that function which we want to write. After
that, we call the close() method of the FileWriter class to close the file stream. After writing
the content and closing the stream, we print a custom message.

If we get any error in the try section, it jumps to the catch block. In the catch block, we
handle the IOException and print a custom message.

Read from a File


The next operation which we can perform on a file is "read from a file". In order to write
data into a file, we will use the Scanner class. Here, we need to close the stream using
the close() method. We will create an instance of the Scanner class

and use the hasNextLine() method


nextLine() method
to get data from the file.

Let's take an example to understand how we can read data from a file.

ReadFromFile.java

1. // Importing the File class


2. import java.io.File;
3. // Importing FileNotFoundException class for handling errors
4. import java.io.FileNotFoundException;
5. // Importing the Scanner class for reading text files
6. import java.util.Scanner;
7.
8. class ReadFromFile {
9. public static void main(String[] args) {
10. try {
11. // Create f1 object of the file to read data
12. File f1 = new File("D:FileOperationExample.txt");
13. Scanner dataReader = new Scanner(f1);
14. while (dataReader.hasNextLine()) {
15. String fileData = dataReader.nextLine();
16. System.out.println(fileData);
17. }
18. dataReader.close();
19. } catch (FileNotFoundException exception) {
20. System.out.println("Unexcpected error occurred!");
21. exception.printStackTrace();
22. }
23. }
24.}

Output:

Expalnation:

In the above code, we import the "java.util.Scannner",


"java.io.File" and "java.io.IOException" classes. We create a class ReadFromFile, and in
its main method, we use the try-catch block. In the try section, we create an instance of
both the Scanner and the File classes. We pass the File class object to the Scanner class
object and then iterate the scanner class object using the "While" loop and print each line of
the file. We also need to close the scanner class object, so we use the close() function. If we
get any error in the try section, it jumps to the catch block. In the catch block, we handle the
IOException and print a custom message.

Delete a File
The next operation which we can perform on a file is "deleting a file". In order to delete a
file, we will use the delete() method of the file. We don't need to close the stream using
the close() method because for deleting a file, we neither use the FileWriter class nor the
Scanner class.

Let's take an example to understand how we can write data into a file.

DeleteFile.java

1. // Importing the File class


2. import java.io.File;
3. class DeleteFile {
4. public static void main(String[] args) {
5. File f0 = new File("D:FileOperationExample.txt");
6. if (f0.delete()) {
7. System.out.println(f0.getName()+ " file is deleted successfully.");
8. } else {
9. System.out.println("Unexpected error found in deletion of the file.");
10. }
11. }
12.}

Output:

Explanation:

In the above code, we import the File class and create a class DeleteFile. In the main()
method of the class, we create f0 object of the file which we want to delete. In
the if statement, we call the delete() method of the file using the f0 object. If the delete()
method returns true, we print the success custom message. Otherwise, it jumps to the else
section where we print the unsuccessful custom message.

All the above-mentioned operations are used to read, write, delete, and create file
programmatically.
Java File: Reading and Writing Files in Java
Java Articles
About File Handling in Java
Reading Ordinary Text Files in Java
Reading Binary Files in Java
Writing Text Files in Java
Writing Binary Files in Java

About File Handling in Java

One this page you can find a simple guide to reading and writing files in the Java programming
language. The code examples here give you everything you need to read and write files right away,
and if you're in a hurry, you can use them without needing to understanding in detail how they work.

File handling in Java is frankly a bit of a pig's ear, but it's not too complicated once you understand a
few basic ideas. The key things to remember are as follows.

You can read files using these classes:

 FileReader for text files in your system's default encoding (for example, files containing
Western European characters on a Western European computer).
 FileInputStream for binary files and text files that contain 'weird' characters.

FileReader (for text files) should usually be wrapped in a BufferedFileReader. This saves up data so
you can deal with it a line at a time or whatever instead of character by character (which usually isn't
much use).

If you want to write files, basically all the same stuff applies, except you'll deal with classes
named FileWriter with BufferedFileWriter for text files, or FileOutputStream for binary files.

Reading Ordinary Text Files in Java

If you want to read an ordinary text file in your system's default encoding (usually the case most of the
time for most people), use FileReader and wrap it in a BufferedReader.

In the following program, we read a file called "temp.txt" and output the file line by line on the console.
//Read a file called "temp.txt" and output the file line by line on the console.
import java.io.*;

public class RDtextfile


{
public static void main(String [] args)
{
// The name of the file to open.
String fileName = "temp.txt";
// This will reference one line at a time
String line = null;
try
{
// FileReader reads text files in the default encoding.
FileReader fileReader = new FileReader(fileName);
// Always wrap FileReader in BufferedReader.
BufferedReader bufferedReader = new BufferedReader(fileReader);
while((line = bufferedReader.readLine()) != null)
{
System.out.println(line);
}
// Always close files.
bufferedReader.close();
}
catch(FileNotFoundException ex)
{
System.out.println("Unable to open file '" + fileName + "'");
}
catch(IOException ex)
{
System.out.println("Error reading file '" + fileName + "'");
// Or we could just do this: ex.printStackTrace();
}
}
}

If "temp.txt" contains this:

I returned from the City about three o'clock on that


May afternoon pretty well disgusted with life.
I had been three months in the Old Country, and was
fed up with it.
If anyone had told me a year ago that I would have
been feeling like that I should have laughed at him;
but there was the fact.
The weather made me liverish,
the talk of the ordinary Englishman made me sick,
I couldn't get enough exercise, and the amusements
of London seemed as flat as soda-water that
has been standing in the sun.
'Richard Hannay,' I kept telling myself, 'you
have got into the wrong ditch, my friend, and
you had better climb out.'

The program outputs this:

I returned from the City about three o'clock on that


May afternoon pretty well disgusted with life.
I had been three months in the Old Country, and was
fed up with it.
If anyone had told me a year ago that I would have
been feeling like that I should have laughed at him;
but there was the fact.
The weather made me liverish,
the talk of the ordinary Englishman made me sick,
I couldn't get enough exercise, and the amusements
of London seemed as flat as soda-water that
has been standing in the sun.
'Richard Hannay,' I kept telling myself, 'you
have got into the wrong ditch, my friend, and
you had better climb out.'

Reading Binary Files in Java

If you want to read a binary file, or a text file containing 'weird' characters (ones that your system
doesn't deal with by default), you need to use FileInputStream instead of FileReader. Instead of
wrapping FileInputStream in a buffer, FileInputStream defines a method called read() that lets you fill
a buffer with data, automatically reading just enough bytes to fill the buffer (or less if there aren't that
many bytes left to read).

Here's a complete example.

import java.io.*;

public class RBinaryfile


{
public static void main(String [] args)
{
// The name of the file to open.
String fileName = "temp.txt";
try
{
// Use this for reading the data.
byte[] buffer = new byte[1000];
FileInputStream inputStream = new FileInputStream(fileName);
// read fills buffer with data and returns the number of bytes read (which of course may be less than the buffer
size, but it will never be more).
int total = 0;
int nRead = 0;
while((nRead = inputStream.read(buffer)) != -1)
{
// Convert to String so we can display it. Of course you wouldn't want to do this with a 'real' binary file.
System.out.println(new String(buffer));
total += nRead;
}
// Always close files.
inputStream.close();
System.out.println("Read " + total + " bytes");
}
catch(FileNotFoundException ex) {
System.out.println("Unable to open file '" + fileName + "'");
}
catch(IOException ex)
{
System.out.println("Error reading file '" + fileName + "'");
// Or we could just do this: ex.printStackTrace();
}
}
}

I returned from the City about three o'clock on that


May afternoon pretty well disgusted with life.
I had been three months in the Old Country, and was
fed up with it.
If anyone had told me a year ago that I would have
been feeling like that I should have laughed at him;
but there was the fact.
The weather made me liverish,
the talk of the ordinary Englishman made me sick,
I couldn't get enough exercise, and the amusements
of London seemed as flat as soda-water that
has been standing in the sun.
'Richard Hannay,' I kept telling myself, 'you
have got into the wrong ditch, my friend, and
you had better climb out.'

Read 649 bytes

Of course, if you had a 'real' binary file -- an image for instance -- you wouldn't want to convert it to a
string and print it on the console as above.
Writing Text Files in Java

To write a text file in Java, use FileWriter instead of FileReader, and BufferedOutputWriter instead
of BufferedOutputReader. Simple eh?

Here's an example program that creates a file called 'temp.txt' and writes some lines of text to it.

import java.io.*;

class Wtextfile
{
public static void main(String [] args)
{
// The name of the file to open.
String fileName = "temp.txt";
try
{
// Assume default encoding.
FileWriter fileWriter =new FileWriter(fileName);
// Always wrap FileWriter in BufferedWriter.
BufferedWriter bufferedWriter =new BufferedWriter(fileWriter);
// Note that write() does not automatically append a newline character.
bufferedWriter.write("Hello there,");
bufferedWriter.write(" here is some text.");
bufferedWriter.newLine();
bufferedWriter.write("We are writing");
bufferedWriter.write(" the text to the file.");
// Always close files.
bufferedWriter.close();
}
catch(IOException ex)
{
System.out.println("Error writing to file '"+ fileName + "'");
// Or we could just do this: ex.printStackTrace();
}
}
}

Writing Binary Files in Java

You can create and write to a binary file in Java using much the same techniques that we used to
read binary files, except that we need FileOutputStream instead of FileInputStream.

In the following example we write out some text as binary data to the file. Usually of course, you'd
probably want to write some proprietary file format or something.

import java.io.*;

public class Rbinfile


{
public static void main(String [] args)
{
// The name of the file to create.
String fileName = "temp.txt";
try
{
// Put some bytes in a buffer so we can write them. Usually this would be image data or something. Or it
might be unicode text.
String bytes = "Hello theren";
byte[] buffer = bytes.getBytes();
FileOutputStream outputStream =new FileOutputStream(fileName);
// write() writes as many bytes from the buffer as the length of the buffer. You can also use write(buffer,
offset, length) if you want to write a specific number of bytes, or only part of the buffer.
outputStream.write(buffer);
// Always close files.
outputStream.close();
System.out.println("Wrote " + buffer.length + " bytes");
}
catch(IOException ex)
{
System.out.println("Error writing file '" + fileName + "'");
// Or we could just do this: ex.printStackTrace();
}
}
}

Wrote 12 bytes
A text file named "List.txt" contains the names of students going to a trip. Write a Method to accept a character in z
and display all those names from List.txt which begins with z.

import java.io.*;
import java.util.*;
class DispalyList
{
public static void main(String args[])throws IOException
{
//-----------------Create List -------------------------------------------------------------------
FileWriter fout=new FileWriter("List.txt");
BufferedWriter ffout=new BufferedWriter(fout);
PrintWriter ob=new PrintWriter(ffout);
Scanner in=new Scanner(System.in);
int i,n;
String name;
System.out.print("\nHow many students : ");
n=in.nextInt();
for(i=1;i<=n;i++)
{
System.out.print("Enter student Name : ");
name=in.next();
ob.println(name);
}
ffout.close();
//-----------------Dispaly List -------------------------------------------------------------------
FileReader fin=new FileReader("List.txt");
BufferedReader ffin=new BufferedReader(fin);
Scanner s1=new Scanner(new File("List.txt"));
System.out.print("\nName i list started with z or Z\n");
while(s1.hasNext())
{
name=s1.next();
if(name.charAt(0)=='z' || name.charAt(0)=='Z')
{
System.out.println(name );
}
}
s1.close();
fin.close();
}
}
A binary file with name "Bank" contains Customer Name, Account No and Balance of its customers. Write a method
that reads data from binary file "Bank" and finds and return the count of customers whose balance is less than N.

import java.io.*;
import java.util.*;
class bankaccount
{
public static void main(String args[])throws IOException
{
Scanner in=new Scanner(System.in);
//--------------------------------------------Write all records-------------------------------------------
int n,i,N,count=0;
System.out.print("\nHow many records : ");
n=in.nextInt();
String cname[]=new String[n];
int account[]=new int[n];
int balance[]=new int[n];
FileOutputStream fos=new FileOutputStream("Bank.dat");
DataOutputStream ob=new DataOutputStream(fos);
for(i=0;i<n;i++)
{
System.out.print("\nEnter name : ");
cname[i]=in.next();
System.out.print("Enter account number : ");
account[i]=in.nextInt();
System.out.print("Enter balance amount : ");
balance[i]=in.nextInt();
ob.writeUTF(cname[i]);
ob.writeInt(account[i]);
ob.writeInt(balance[i]);
}
ob.close();
fos.close();
//--------------------------------------------Dispaly all records-------------------------------------------
FileInputStream fin=new FileInputStream("Bank.dat");
DataInputStream ffin=new DataInputStream(fin);
String cname1;
int account1,balance1;
boolean eof=false;
System.out.print("Enter the amount above which your want to display details of customer : ");
N=in.nextInt();
while(!eof)
{
try
{
cname1=ffin.readUTF();
account1=ffin.readInt();
balance1=ffin.readInt();
if(balance1>N)
{
System.out.print("\nName : "+cname1+"\tAccount Number : "+account1+"\tBalance : "+balance1);
count++;
}
}
catch(EOFException e)
{
System.out.print("\nEnd of file encounted");
eof=true;
}
}
System.out.print("\nNumber of records : "+ count);
ffin.close();
}
}

You might also like