DEV Community

Cover image for File Operations In JAVA
Nirmit Gupta
Nirmit Gupta

Posted on

File Operations In JAVA

File handling is one of the most important aspects in world of coding.
In JAVA we can perform the following by JAVA I/O API.

File handling enables one to perform various operations related to create, read, delete, update a file.

Before jumping into file handling lets understand the concept of Streams in JAVA.

Streams

Streams are a sequence of character.
There are two types of streams in JAVA.
1.) Input Stream — The input stream is used to read data from a file.
It is an abstract class which provides common definition to be used by subclasses. We have various subclasses of InputStream such as —
.)AudioInputStream — It is used to read or manipulate audio data.

.)ByteArrayInputStream — Used to read byte array data as stream.

.)FileInputStream — This input stream subclass is used to read and manipulate data from files.

.)FilterInputStream — Provide additional functionality like buffering or data transformation.

.)StringBufferInputStream — Stream to read data from a string buffer.

.)ObjectInputStream — Used to read and deserialize objects from an input stream.

2.)Output Stream — The output stream is used to write data to various output devices such as monitor,file and many more.It is also an abstract class with various subclasses.

.)ByteArrayOutputStream
.)FileOutputStream
.)StringBufferOutputStream
.)ObjectOutputStream
.)DataOutputStream
.)PrintStream

Based on data we have two types of streams.

.)Byte Stream- This stream is used to read/write byte data.

.)Character Stream- This stream is used to read/write character data.

Since one has got idea on Streams and various stuff around it, lets comeback to File Handling in JAVA.

Lets see a few methods related to file handling which will give idea of what all we can do in file handling.

.)canRead() — This method returns a boolean value which tells whether a file is readable or not.

.)createNewFile() — This method returns a boolean value and creates a new file.

.)delete() — This method returns a boolean value and deletes a file.

.)getName() — This method returns a string value which is the name of the file.

.)getAbsolutePath() — This method returns a string value which is the absolute path of the file.

.)length() — This method returns a long value which is the size of the file.

.)list() — This method returns a string array which contains names of all files present in the directory.

.)mkdir() — This method returns a boolean value and create a new directory.

.)canWrite() —This method returns a boolean value and checks whether we can write data into a file or not.

.)exists() — This method return a boolean value and checks whether a file exists or not.

With files one can do CRUD operations which are -
.)Create a file

import java.io.File;
import java.io.IOException;

public class CreateFile {
    public static void main(String args[]) {
        try {
            // Create an object of a file
            File file = new File("Example.txt");
            //Check whether file exists or not
            if (file.createNewFile()) {
                System.out.println("File " + file.getName() + " got created successfully.");
            } else {
                System.out.println("File already exists in the directory.");
            }
        } catch (IOException exception) {
            System.out.println("Unexpected error is occurred.");
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

Output

File Example.txt got created successfully.
Enter fullscreen mode Exit fullscreen mode

.)Read a file

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class ReadAFile {
    public static void main(String[] args) {
        File file = new File("Example.txt");
        try {
            Scanner sc = new Scanner(file);

            //Reading the file
            while (sc.hasNextLine()) {
                String data = sc.nextLine();
                System.out.println(data);
            }
            sc.close();
        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

Output

Hello World
Enter fullscreen mode Exit fullscreen mode

.)Write/Update a file

import java.io.FileWriter;

public class WriteAFile {
    public static void main(String[] args) {
        try {
            FileWriter file = new FileWriter("Example.txt");
            file.write("Hello World");

            //Close the stream
            file.close();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

.)Delete a file

import java.io.File;

public class DeleteAFile {
    public static void main(String[] args) {
        File file = new File("Example.txt");
        try {
            if(file.delete()){
                System.out.println("File deleted successfully");
            }
            else{
                System.out.println("Exception occurred while deleting the file");
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

Output

File deleted successfully
Enter fullscreen mode Exit fullscreen mode

This marks the end of the tutorial.

In summary JAVA provides a robust mechanism to handle file operations in JAVA which makes development easy.My suggestion would be to explore more in this topic and play with more methods for better grasp of the topic.
I hope the above tutorial provides some value to the reader and if you find this tutorial useful, do leave a comment and share it with fellow developers.

!!Happy Learning.Happy Coding!!

Top comments (1)

Collapse
 
ankityadav profile image
Ankit Yadav

We are looking for a Java Developer (Freelancer)

We have an Online Auction Platform for Artworks, where users can buy and sell artworks via auctions. The platform includes bidding functionality, live auction timers, and an artwork catalog.

Skills Needed: Java
Budget: $470

Share your proposal at:
🔗 myexpertify.com/project/67ab90921f...

Java #FreelanceDeveloper #AuctionPlatform #SoftwareDevelopment #FreelanceProject