Full Stack Web Development Internship Program
- 5k Enrolled Learners
- Weekend/Weekday
- Live Class
Java being one of the most popular programming languages provides extensive support to various functionalities like database, sockets, etc. One such functionality is File Handling in Java. File Handling is necessary to perform various tasks on a file, such as read, write, etc. In this article, I will tell you what are the various file operations in Java.
Below topics are covered in this article:
What is File Handling in Java?
File handling in Java implies reading from and writing data to a file. The File class from the java.io package, allows us to work with different formats of files. In order to use the File class, you need to create an object of the class and specify the filename or directory name.
For example:
// Import the File class import java.io.File // Specify the filename File obj = new File("filename.txt");
Java uses the concept of a stream to make I/O operations on a file. So let’s now understand what is a Stream in Java.
What is a Stream?
In Java, Stream is a sequence of data which can be of two types.
This mainly incorporates with byte data. When an input is provided and executed with byte data, then it is called the file handling process with a byte stream.
Character Stream is a stream which incorporates with characters. Processing of input data with character is called the file handling process with a character stream.
Now that you know what is a stream, let’s dive deeper into this article on File Handling in Java and know the various methods that are useful for operations on the files like creating, reading and writing.
Below table depicts the various methods that are used for performing operations on Java files.
Method | Type | Description |
---|---|---|
canRead() | Boolean | It tests whether the file is readable or not |
canWrite() | Boolean | It tests whether the file is writable or not |
createNewFile() | Boolean | This method creates an empty file |
delete() | Boolean | Deletes a file |
exists() | Boolean | It tests whether the file exists |
getName() | String | Returns the name of the file |
getAbsolutePath() | String | Returns the absolute pathname of the file |
length() | Long | Returns the size of the file in bytes |
list() | String[] | Returns an array of the files in the directory |
mkdir() | Boolean | Creates a directory |
Let’s now understand what are the various file operations in Java and how to perform them.
Basically, you can perform four operations on a file. They are as follows:
Now, let’s get into the details of each of these operations
In this case, to create a file you can use the createNewFile() method. This method returns true if the file was successfully created, and false if the file already exists.
Let’s see an example of how to create a file in Java.
package FileHandling; // Import the File class import java.io.File; // Import the IOException class to handle errors import java.io.IOException; public class CreateFile { public static void main(String[] args) { try { // Creating an object of a file File myObj = new File("D:FileHandlingNewFilef1.txt"); if (myObj.createNewFile()) { System.out.println("File created: " + myObj.getName()); } else { System.out.println("File already exists."); } } catch (IOException e) { System.out.println("An error occurred."); e.printStackTrace(); } } }
In the above code, a file named NewFilef1 gets created in the specified location. If there is an error, then it gets handled in the catch block. Let’s check the output on executing the above code:
Output:
File created: NewFilef1.txt
Having understood this, let’s see how to get File information.
2. Get File information
Let’s see how to get file information using various methods with the help of below example code
package FileHandling; import java.io.File; // Import the File class public class FileInformation { public static void main(String[] args) { // Creating an object of a file File myObj = new File("NewFilef1.txt"); if (myObj.exists()) { // Returning the file name System.out.println("File name: " + myObj.getName()); // Returning the path of the file System.out.println("Absolute path: " + myObj.getAbsolutePath()); // Displaying whether the file is writable System.out.println("Writeable: " + myObj.canWrite()); // Displaying whether the file is readable or not System.out.println("Readable " + myObj.canRead()); // Returning the length of the file in bytes System.out.println("File size in bytes " + myObj.length()); } else { System.out.println("The file does not exist."); } } }
When you execute the above program, you will get the file information as shown in the output below:
Output:
File name: NewFilef1.txt Absolute path: D:FileHandlingNewFilef1.txt Writable: true Readable true File size in bytes 52
This is how you need to write a program to get the information of the specific file. Now let’s move further and see two more operations on the file. i.e. read and write operations.
3. Write to a File
In the following example, I have used the FileWriter class together with its write() method to write some text into the file. Let’s understand this with the help of a code.
package FileHandling; // Import the FileWriter class import java.io.FileWriter; // Import the IOException class to handle errors import java.io.IOException; public class WriteToFile { public static void main(String[] args) { try { FileWriter myWriter = new FileWriter("D:FileHandlingNewFilef1.txt"); // Writes this content into the specified file myWriter.write(Java is the prominent programming language of the millenium!"); // Closing is necessary to retrieve the resources allocated myWriter.close(); System.out.println("Successfully wrote to the file."); } catch (IOException e) { System.out.println("An error occurred."); e.printStackTrace(); } } }
Output:
Successfully wrote to the file
When you run the file, the above text, “Java is the prominent programming language of the millennium!” will be entered in the file that you have created. You can cross check it by opening the file in the specified location.
Now let’s move further and understand the last operation on the file, i.e. Read a file
In the following example, I have used the Scanner class to read the contents of the text file.
package FileHandling; // Import the File class import java.io.File; // Import this class to handle errors import java.io.FileNotFoundException; // Import the Scanner class to read text files import java.util.Scanner; public class ReadFromFile { public static void main(String[] args) { try { // Creating an object of the file for reading the data File myObj = new File("D:FileHandlingNewFilef1.txt"); Scanner myReader = new Scanner(myObj); while (myReader.hasNextLine()) { String data = myReader.nextLine(); System.out.println(data); } myReader.close(); } catch (FileNotFoundException e) { System.out.println("An error occurred."); e.printStackTrace(); } } }
When you execute the above program, it will display the content present in the given file.
Output:
Java is the prominent programming language of the millennium!
That’s how it works. So, this was all about the various file operations in Java. With this, we come to an end of this article on File Handling in Java. I hope you found it informative. If you wish to learn more, you can check out our other Java Blogs as well.
Check out the Java Certification Training by Edureka, a trusted online learning company with a network of more than 250,000 satisfied learners spread across the globe. We are here to help you with every step on your journey, for becoming a besides this java interview questions, we come up with a curriculum which is designed for students and professionals who want to be a Java Developer.
Got a question for us? Please mention it in the comments section of this “File Handling in Java” article and we will get back to you as soon as possible or you can also join our Java Training in Sheffield.
Course Name | Date | |
---|---|---|
Java Certification Training Course | Class Starts on 28th January,2023 28th January SAT&SUN (Weekend Batch) | View Details |
Java Certification Training Course | Class Starts on 25th February,2023 25th February SAT&SUN (Weekend Batch) | View Details |
edureka.co