Java is a broadly well-liked programming language. Moreover strong structure and parts, some of the important causes behind its success and recognition is its help for quite a few functionalities. File dealing with in Java is one such performance that enables us to work with information. Right now, we shall be studying about varied operations we will carry out with the file ideas in Java.
What's Java File Dealing with?
As talked about, file dealing with in Java lets you work with information. It's a Java performance outlined within the File class of the Java.io bundle. The io in Java.io bundle stands for Enter and Output. One can find all of the lessons you'll ever have to carry out any enter or output operations within the Java.io bundle.
You possibly can entry and use this File class to carry out varied capabilities by creating an object and offering the file or listing identify. The syntax to create an object and use the File class is:
import java.io.File;
File obj = new File(“name.txt”);
As seen within the above syntax, you first have to import the File class from the Java.io bundle. As soon as imported, all you want to do is create an object and specify the file or listing identify you need to work with. To say the listing identify in a Home windows OS, you must use “.” For example, you must use “C:UsersMyFolderMySubFolder” and never “C:Users|MyFolder|MySubFolder.” Nevertheless, for different working methods similar to Linux, you should use the only as standard.
All of the I/O (Enter/Output) operations of the file ideas in Java are carried out with the assistance of a stream. Let’s delve deep into what's a stream, and the way are these operations carried out with it?
What's the Idea of Streams in Java?
In easier phrases, a stream is a collection of information. There are two sorts of stream, that are:
- Byte stream: Any such stream works with byte knowledge. The I/O operations are carried out with a byte stream if you learn or write knowledge within the byte (8-bit) format.
- Character stream: Any such stream works with character sequence. The I/O operations are carried out with a personality stream if you end up studying or writing knowledge utilizing characters.
Checkout: Prime Java Tasks on GitHub
What are the Totally different Strategies Out there for File Dealing with in Java?
The File class gives varied predefined strategies that can assist you carry out all of the I/O operations by merely calling them. The beneath desk exhibits all of the strategies, together with the actions they carry out.
Technique | Sort | Description |
canRead() | Boolean | It checks whether or not you possibly can learn the file or not. |
canWrite() | Boolean | It exams whether or not you possibly can write into the file or not. |
createNewFile() | Boolean | This can create a brand new empty file. |
delete() | Boolean | This methodology will delete the desired file. |
exists() | Boolean | It checks if the talked about file exists. |
getName() | String | Returns file’s identify. |
getAbsolutePath() | String | Returns the file’s absolute pathname. |
size() | Lengthy | It returns the file’s measurement in bytes. |
record() | String[] | Returns an inventory of file names current within the listing. |
mkdir() | Boolean | This methodology will create a brand new listing. |
How you can Carry out Totally different Java File Dealing with Operations?
Since you recognize concerning the totally different strategies out there within the File class, it’s time to make use of them to carry out varied Java file dealing with operations. To start with, you possibly can full the next actions on a file.
- Create a brand new file.
- Get file data.
- Write right into a file.
- Learn from a file.
- Delete a file.
We shall be going by an instance to carry out every of those operations. Within the first instance, we are going to create a brand new file after which use the identical file to carry out different duties.
Making a File
You possibly can create a file with the createNewFile() methodology. Executing the tactic will return both true or false. If the file is created efficiently, it'll return a real. However, if the file already exists, it'll return a false.
It's all the time suggested to make use of this methodology inside a attempt to catch block as it may throw an exception if the file isn't created efficiently. You possibly can study extra about it in our information on exception dealing with in Java. See the beneath instance that makes use of the createNewFile() methodology to create a brand new empty file.
import java.io.File; // Importing the File class
import java.io.IOException; // Importing the IOException class for dealing with errors
public class CreateFileExample{
public static void important(String[] args){
strive{
File obj = new File(“newFile.txt”);
if(obj.createNewFile()){ // if it returns true, i.e., efficiently created
System.out.println(“The ile is created successfully:” + obj.getName());
}
else{ // if it returns false, i.e., file already exists
System.out.println(“File already exists”);
}
}
catch (IOException e){ // to catch exceptions if any error happens
System.out.println(“Error occurred”);
e.printStackTrace();
}
}
}
Output:
The file is created efficiently: newFile.txt
Getting File Info
You should use varied strategies outlined within the File class to entry the file’s totally different data, similar to identify, size, absolute path, readable, and extra. A few of the strategies to get file data are used within the beneath instance.
import java.io.File;
public class AccessInfoExample{
public static void important(String[] args){
// Creating an object
File obj = new File(“newFile.txt”);
if(obj.exists()){
// Getting file identify
System.out.println(“The name of the file is:” + obj.getName());
// Getting absolute path
System.out.println(“The absolute path of the file is:” + obj.getAbsolutePath());
// Checking if file is writable
System.out.println(“Is the file writable?” + obj.canWrite());
// Checking if file is readable
System.out.println(“Is the file readable?” + obj.canRead());
// Getting the size in bytes
// It would present 0 as we haven’t written something in our file but
System.out.println(“File size in bytes:” + obj.size());
}
else{
System.out.println(“File named” + obj.getName() + “does not exist.”);
}
}
}
Output:
The identify of the file is: newFile.txt
Absolutely the path of the file is: D:JavaProgramming:newFile.txt
Is the file writable? true
Is the file readable? true
File measurement in bytes: 0
The above instance’s output might fluctuate relying on the file’s identify, the trail the place you saved it, and the dimensions. If the desired file doesn't exist, it'll present “File named newFile.txt does not exist.”
Writing Right into a File
To write down bytes knowledge, use the FileOutputStream class, and for characters, use the FileWriter class. Within the beneath instance, we are going to use the FileWriter class and its predefined write() methodology to put in writing one thing inside our “newFile.”
One factor to notice earlier than beginning with the instance is that everytime you open a file for writing, you want to shut it with the shut() methodology. Closing the file will assist you to retrieve the assets allotted by the Java compiler to put in writing in a file. Let’s take a look at how one can do it within the instance.
import java.io.FileWriter; // Importing the FileWriter class
import java.io.IOException; // Importing the IOException class for dealing with errors
public class WriteExample{
public static void important(String[] args){
strive{
FileWriter obj = new FileWriter(“newFile.txt”);
obj.write(“This will be written in the newFile.txt file!”);
obj.shut(); // Closing the file
System.out.println(“We have successfully written in the file and closed it.”);
}
catch(IOException e){
System.out.println(“Error occurred.”);
e.printStackTrace();
}
}
}
Output:
We've got efficiently written within the file and closed it.
Studying From a File
You should use FileInputStream to learn bytes knowledge and FileReader to learn characters knowledge from a file. Alternatively, you too can use the Scanner class to learn from a file. Since we have now already used the FileWriter to put in writing knowledge, we are going to use the Scanner class to learn knowledge on this instance. Like whereas writing, closing the opened file is important whereas studying as properly.
import java.io.File; // Importing the File class
import java.io.FileNotFoundException; // Importing the category for dealing with errors
import java.util.Scanner; // Importing the Scanner class for studying textual content information
public class ReadExample{
public static void important(String[] args){
strive{
File obj = new File(“newFile.txt”);
Scanner robj = new Scanner(obj);
whereas (robj.hasNextLine()){
String dataInfo = robj.nextLine();
System.out.println(dataInfo);
}
robj.shut();
}
catch(FileNotFoundException e){
System.out.println(“Error occurred.”);
e.printStackTrace();
}
}
}
Output:
This shall be written within the newFile.txt file!
Deleting a File
You possibly can delete a file through the use of the delete() methodology of the File class. You may also delete a whole folder whether it is empty. Let’s delete our “newFile.txt” file within the beneath instance.
import java.io.File; // Import the File class
public class DeleteExample{
public static void important(String[] args){
File obj = new File(“newFile.txt”);
if(obj.delete()){
System.out.println(“The file named” + obj.getName() + “is deleted successfully.”);
}
else{
System.out.println(“File not deleted.”);
}
}
}
Output:
The file named newFile.txt is deleted efficiently.
Additionally Learn: Java Venture Concepts & Matters
Conclusion
On this submit, you realized every part about file dealing with in Java. Java gives varied such functionalities, which makes it some of the well-liked programming languages worldwide. Therefore, it's no shock that Java builders’ wage in India could be very excessive. If you wish to develop into a Java developer and get a excessive wage bundle, upGrad’s free Java on-line course is apt for you.
The course is part of the upStart program, a priceless upskilling initiative. As soon as you might be carried out with the free course and get the certification, you possibly can additional go for upGrad’s PG Certification in Full-Stack Improvement. You get 400+ hours of studying materials with hands-on expertise by initiatives. Take the course and excel within the area of software program growth with Java programming ideas.
Land on Your Dream Job
UPGRAD AND IIIT-BANGALORE'S PG DIPLOMA IN SOFTWARE DEVELOPMENT
APPLY NOW