File Handling

File handling is very important topic in Java. We need to perform various tasks like create file, read and write file, modify file, delete file, etc. We will cover below topics in this article.

  1. What is file handling in Java
  2. What is file stream
  3. Several Java file methods
  4. File operations in java

What is file handling in Java

File handling is a term that used to manipulate files. We can create, read, update and delete files from the java.io package. In order to manipulate any file, you have to create an object and declare file path in constructor.

What is file stream

Stream is a sequence of data that is used for mentioning if it is text type of image/video type.

File stream mainly 2 types:

  1. Byte Stream: Byte stream is a stream that incorporates byte data. Image/video file manipulation can be an example of byte stream.
  2. Character stream: Character stream is a stream that incorporates character data. txt file, JSON, excel, etc file manipulation can be an example of a character stream.

Several Java file methods

MethodTypeDescription
canRead()Booleanchecks if a file is readable of not
canWrite()Booleanchecks if a file is writable or not
createNewFile()Booleancreates an empty file
delete()Booleandelete a file
exists()Booleancheck if a file exists or not
getName()Stringreturn name of a file
getAbsolutePath()Stringreturn absolute path of a file
length()Longreturn the size of the file in bytes
list()String[]return array of the files in a directory
mkdir()Booleancreates a directory

File operations in java

We can perform 4 types of operation over a file.

  1. Create a new file
  2. Write something in the file
  3. Read data from the file
  4. Get file information

Create a new file

We will create a file using createNewFile() method in java.

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

public class Main {
    public static void main(String[] args) throws IOException {
        File file = new File("TestFile.txt"); //mention file path using constructor
        if (file.createNewFile()) {
            System.out.println("File created: " + file.getName());
        } else {
            System.out.println("File already exists.");
        }
    }

}

After executing the code, you can see TestFile.txt file has been created on your project home directory.

Output:
File created: TestFile.txt

Write something in the file

Now we will write something on the created file.

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

public class Main {
    public static void main(String[] args) throws IOException {
        String fileName="TestFile.txt";
        File file = new File(fileName); //mention file path using constructor
        FileWriter fileWriter = new FileWriter(fileName);
        fileWriter.write("This is a sample test. Hello Java! Java is very interesting and easy to learn.");
        fileWriter.close();
        if (file.createNewFile()) {
            System.out.println("File created: " + file.getName());
        } else {
            System.out.println("File already exists.");
        }
        System.out.println("Successfully wrote to the file");
    }


}

After executing above code, you will see, the text has been written on the file.

Output:
File already exists.
Successfully wrote to the file

Read data from the file

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

public class Main {
    public static void main(String[] args) throws IOException {
        String fileName="TestFile.txt";
        File file = new File(fileName); //mention file path using constructor
        Scanner myReader = new Scanner(file);
        while (myReader.hasNextLine()) {
            String data = myReader.nextLine();
            System.out.println(data);

        }
        myReader.close();
    }

}

After executing above code, you can read data from the file.

Output:
This is a sample test. Hello Java! Java is very interesting and easy to learn.

Get file information:

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

public class Main {
    public static void main(String[] args) throws IOException {
        String fileName="TestFile.txt";
        File file = new File(fileName); //mention file path using constructor
        System.out.println("File Name: "+ file.getName());
        System.out.println("File Path: "+file.getAbsolutePath());
        System.out.println("FIle size in bytes: "+file.length());

    }

}

After executing above file, you will get the file name, file path and file size.

Output:
File Name: TestFile.txt
File Path: D:\Java Practice\TestFile.txt
FIle size in bytes: 78
about author

admin

salmansrabon@gmail.com

If you like my post or If you have any queries, do not hesitate to leave a comment.

Leave a Reply

Your email address will not be published. Required fields are marked *