Tutorial Playlist
Java, one of the most popular programming languages, supplies extensive support to numerous functional operations like file handling, database, sockets, etc. File handling in Java is a crucial function that allows you to conduct different tasks on a stored file, such as writing, reading, etc.
This tutorial presents a thorough synopsis of file handling and its functionality in Java.
You can work with files in Java by using the File Class inside the java.io package. Generating an object of the class and then adding a specified name to the file allows you to use the File Class. File handling in Java primarily stands for reading from, followed by writing data to a particular file.
The File Class lets you perform various operations on different file formats once an object of the class with a specific filename or directory name is created. File handling presents you with several benefits, such as:
Java uses the concept of streams to conduct I/O operations on its files. Hence, the streams play an important role in the file-handling operations of Java.
In Java, a stream is a sequence of data used to perform I/O operations on files. Based on the functional aspects, streams can be categorized into two types, namely:
The stream API is used for processing groups of data. JavaScript can programmatically access the streams of data received over the network using stream API. It also allows Java to process the data streams as per the developer's requirements.
Stream API can also be divided into two categories depending on the data type, which are:
Let us write a program that copies the contents of a file named "source.txt" to another file named "destination.txt".
We will first create the source.txt file and put the text ‘upGrad teaches programming.’ in this file. It is also important to note that we must create the java (upGradTutorials.java) file in the same directory as the source.txt file.
Then, we will run the program below:
import java.io.*;
public class CopyFileExample {
public static void main(String[] args) {
try {
File sourceFile = new File("source.txt");
File destinationFile = new File("destination.txt");
FileReader fileReader = new FileReader(sourceFile);
FileWriter fileWriter = new FileWriter(destinationFile);
BufferedReader bufferedReader = new BufferedReader(fileReader);
BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);
String line;
while ((line = bufferedReader.readLine()) != null) {
bufferedWriter.write(line);
bufferedWriter.newLine();
}
bufferedReader.close();
bufferedWriter.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Once we run the program, a new file destination.txt will get created in the directory with the same text.
The code begins by creating two File objects: sourceFile represents the source file ("source.txt"), and destinationFile represents the destination file ("destination.txt"). A FileReader and FileWriter are created to read from the source file and write to the destination file. BufferedReader and BufferedWriter are used for efficient reading and writing.
Inside the while loop, each source file line is read using readLine() and written to the destination file using write(). The newLine() method is used to insert line breaks. The loop continues until there are no more lines to read from the source file. Finally, the BufferedReader and BufferedWriter are closed to flush the buffers and release system resources.
Now, let us write a program that reads the contents of a file named "upGrad.txt" and prints each line to the console.
We will first create the upGrad.txt file and put the text ‘upGrad teaches Java programming.’ inside this file. Then, we will create the java (upGradTutorials.java) file in the same directory as the txt file.
Once we run the program, it will read the contents of the upGrad.txt file and print each line to the console.
import java.io.*;
public class upGradTutorials {
public static void main(String[] args) {
try {
File file = new File("upGrad.txt");
FileReader fileReader = new FileReader(file);
BufferedReader bufferedReader = new BufferedReader(fileReader);
String line;
while ((line = bufferedReader.readLine()) != null) {
System.out.println(line);
}
bufferedReader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
This program begins by creating a File object representing the file "upGrad.txt". Then, a FileReader is created to read the contents of the file, and a BufferedReader is used to read the text efficiently. Within a while loop, each line of the file is read and stored in the variable line.
The loop continues until there are no more lines to read (i.e., readLine() returns null). For each line, the program prints it to the console. Finally, the BufferedReader is closed to release system resources and handle any potential exceptions.
We have learned how to read files in Java, let us now learn how to write a program that will first create a ‘upGrad.txt’ file and then write the two strings of text ‘upGrad teaches programming.’ and ‘upGrad teaches Java.’ in that txt file.
Contents of the created txt file:
import java.io.*;
public class upGradTutorials {
public static void main(String[] args) {
try {
File file = new File("upGrad.txt");
FileWriter fileWriter = new FileWriter(file);
BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);
bufferedWriter.write("Hello, World!");
bufferedWriter.newLine();
bufferedWriter.write("This is a sample text.");
bufferedWriter.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
This program begins by creating a File object representing the file "upGrad.txt". Next, a FileWriter is created to write the file's contents, and a BufferedWriter is used to write the text efficiently.
The program then uses the write() method of the BufferedWriter to write the string "upGrad teaches programming." to the file. The newLine() method moves the cursor to the next line. Another string, "upGrad teaches Java." is written to the file. Finally, the BufferedWriter is closed to flush the buffer and release system resources.
Here are some commonly used methods in the File class for file handling:
This code creates a new file named "upGrad.txt" using the createNewFile() method. If the file is successfully created, it prints a message indicating so. If the file already exists, it prints a message stating it already exists.
import java.io.File;
import java.io.IOException;
public class upGradTutorials {
public static void main(String[] args) {
try {
File file = new File("upGrad.txt");
if (file.createNewFile()) {
System.out.println("File created: " + file.getName());
} else {
System.out.println("File already exists.");
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
This code deletes a file named "upGrad.txt" using the delete() method. If the file is successfully deleted, it prints a message indicating so. If the deletion fails, it prints a message stating that the file couldn't be deleted.
import java.io.File;
public class upGradTutorials {
public static void main(String[] args) {
File file = new File("upGrad.txt");
if (file.delete()) {
System.out.println("File deleted: " + file.getName());
} else {
System.out.println("Failed to delete the file.");
}
}
}
This code renames a file named "example.txt" to "upGrad.txt" using the renameTo() method. If the renaming is successful, it prints a message indicating so. If the renaming fails, it prints a message stating that the file couldn't be renamed.
import java.io.File;
public class upGradTutorials {
public static void main(String[] args) {
File oldFile = new File("example.txt");
File newFile = new File("upGrad.txt");
if (oldFile.renameTo(newFile)) {
System.out.println("File renamed successfully.");
} else {
System.out.println("Failed to rename the file.");
}
}
}
This code checks the attributes of a file named "upGrad.txt" using the File class. It first checks if the file exists using the exists() method. If the file exists, it prints the file name, absolute path, size, last modified timestamp, and whether it is a directory or a regular file. If the file doesn't exist, it prints a message indicating it doesn't exist.
import java.io.File;
public class upGradTutorials {
public static void main(String[] args) {
File file = new File("upGrad.txt");
if (file.exists()) {
System.out.println("File name: " + file.getName());
System.out.println("File path: " + file.getAbsolutePath());
System.out.println("File size: " + file.length() + " bytes");
System.out.println("Last modified: " + file.lastModified());
System.out.println("Is directory? " + file.isDirectory());
System.out.println("Is file? " + file.isFile());
} else {
System.out.println("File does not exist.");
}
}
}
You can perform several operations on a file in Java. The four major operations include creating a file, getting file information, writing to a file, and reading from a file. These activities can be easily accomplished using the different techniques of file handling in Java.
A comprehensive course can help you if you want to gain deeper insight into file handling and other operations in Java. upGrad offers curated courses on Java that can increase your expertise on the subject. Enrolling in these courses allows you to gain more knowledge about the core Java concepts.
1. What are file handling methods?
File handling is the process of storing the available data or information in a file with the assistance of a program. In Java, you can store the entire available data of a program inside a file with the help of file handling. The data can be retracted or fetched back from the files whenever you need them, whereas using file handling in Java allows you to operate the stored files in another program.
2. How to perform file handling in Java?
You can get all the classes required for performing every input and output operation in Java from the java.io package. The Java I/O API allows you to work with file handling in Java.
3. Why is a string immutable in Java?
Strings that contain the same values try to minimize unwanted copies of the content, which makes them share the storage of a single pool. Once a string is created, its internal content cannot be further changed since adding any changes to its values leads to creating a new string. This explains why strings in Java are immutable or unchangeable.
PAVAN VADAPALLI
Popular
Talk to our experts. We’re available 24/7.
Indian Nationals
1800 210 2020
Foreign Nationals
+918045604032
upGrad does not grant credit; credits are granted, accepted or transferred at the sole discretion of the relevant educational institution offering the diploma or degree. We advise you to enquire further regarding the suitability of this program for your academic, professional requirements and job prospects before enrolling. upGrad does not make any representations regarding the recognition or equivalence of the credits or credentials awarded, unless otherwise expressly stated. Success depends on individual qualifications, experience, and efforts in seeking employment.
upGrad does not grant credit; credits are granted, accepted or transferred at the sole discretion of the relevant educational institution offering the diploma or degree. We advise you to enquire further regarding the suitability of this program for your academic, professional requirements and job prospects before enr...