DEV Community

KIRAN RAJ
KIRAN RAJ

Posted on

Java File Handling

Java File Handling

What I understood about File Handling

When I started learning Java, one thing I noticed is that data inside a program does not stay forever. Once the program stops, everything is gone. Because of that, we use files to store data.

So, file handling is basically working with files like creating them, writing something into them, reading the content later, and sometimes deleting them.


File Class (Basic Idea)

In Java, we usually use the File class from the java.io package. It is mainly used to refer to a file path.

One small confusion I had at first was thinking it creates a file directly. But actually, it just creates an object that points to a location.

import java.io.File;

public class Test {
    public static void main(String[] args) {
        File myFile = new File("data.txt");
        System.out.println("Just created a reference, not the actual file");
    }
}
Enter fullscreen mode Exit fullscreen mode

Creating the File

To actually create the file in the system, we use createNewFile().

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

public class FileCreate {
    public static void main(String[] args) {
        try {
            File myFile = new File("data.txt");

            if (myFile.createNewFile()) {
                System.out.println("New file created");
            } else {
                System.out.println("File already exists");
            }

        } catch (IOException e) {
            System.out.println("Something went wrong while creating file");
        }
    }
}

Enter fullscreen mode Exit fullscreen mode

Writing into the File

To write something into the file, we can use FileWriter. One important thing is to close it after writing.

import java.io.FileWriter;

public class FileWrite {
    public static void main(String[] args) {
        try {
            FileWriter writer = new FileWriter("data.txt");

            writer.write("This is just a practice example.");
            writer.close();

            System.out.println("Writing done");

        } catch (Exception e) {
            System.out.println("Error while writing");
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

Reading the File

For reading, I used Scanner because it is easy to understand. It reads line by line.

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

public class FileRead {
    public static void main(String[] args) {
        try {
            File myFile = new File("data.txt");
            Scanner sc = new Scanner(myFile);

            while (sc.hasNextLine()) {
                System.out.println(sc.nextLine());
            }

            sc.close();

        } catch (Exception e) {
            System.out.println("Could not read the file");
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

Deleting the File

If the file is not needed, we can delete it using delete().

import java.io.File;

public class FileDelete {
    public static void main(String[] args) {
        File myFile = new File("data.txt");

        if (myFile.delete()) {
            System.out.println("File deleted successfully");
        } else {
            System.out.println("Delete failed");
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

Streams (Just Basic Understanding)

While reading about this, I found that Java uses streams internally.

Byte streams - used for images or other binary data

Character streams - used for text

Some classes I came across are FileReader and FileWriter.


Errors I Faced

While trying these programs, I got errors like file not found and sometimes permission issues. Using try-catch helped me handle those errors.


Conclusion (My Understanding)

File handling is simple once we practice it. At first it felt confusing, but after trying examples, it became clear how Java works with files.

I feel practicing small programs is the best way to understand this topic.

Top comments (0)