File Operations in Java 11

Download as pdf or txt
Download as pdf or txt
You are on page 1of 9

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


file or not.

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

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


the file or not.

4. exists() Boolean The exists() method is used to check whether the spec
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. getAbsolutePath() String The getAbsolutePath() method is used to get the abso


file.

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

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

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 t
o 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.

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy