File
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.
4. exists() Boolean The exists() method is used to check whether the specified
file is present or not.
6. getName() String The getName() method is used to find the file name.
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.
CreateFile.java
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.
Let's take an example to understand how to use file methods to get the information of the
file.
FileInfo.java
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:
Let's take an example to understand how we can write data into a file.
WriteToFile.java
Output:
Explanation:
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.
Let's take an example to understand how we can read data from a file.
ReadFromFile.java
Output:
Expalnation:
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
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
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.
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.
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.*;
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).
import java.io.*;
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();
}
}
}
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.*;
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();
}
}