File Handling in Java

What is File in Java?


There is more to the Java concept of a file than merely a file on a hard drive. It stands for any resource that has the ability to be read from or written to, such as actual disk files, input/output devices like consoles or terminals, printers, or even network connections.

To process a file within a program, a logical file must be created in RAM. This logical file is essentially an object of a file data type. Java's I/O system provides a consistent interface for file operations, regardless of the underlying device.

A stream is generally a sequence of data and serves as an abstraction between the programmer and the actual device (file). Streams are categorized into two types:

Text Stream

Treat data as text, sequences of characters. It can be used for console input and output, reading and writing text files, and more.

Reader and Writer classes such as BufferedReader, FileReader, BufferedWriter, and FileWriter are a few examples.

Binary Stream

Treat data as raw byte sequences. For non-text files, such as audio or picture files, or any other file whose data cannot be changed (no character translation), this is used.

InputStream and OutputStream classes, such as FileInputStream and FileOutputStream, are two examples.

File input output in Java

whether reading configuration files, storing user data, logging information, or handling large datasets—is a crucial aspect of many Java applications. Java’s comprehensive java.io package provides a rich set of classes and interfaces that make file input/output operations efficient, flexible, and easy to implement.

Reading data

Java offers a number of classes for flexible and efficient input data reading. The format of the data and the input's source determine the option. The main classifications you mentioned are broken down as follows:

BufferedReader

By buffering the input, this reader effectively reads characters from an input stream. Because each read operation may require interacting with the underlying system (disk, network, etc.), reading data from a file or input source character-by-character or byte-by-byte can be slow. Buffering reduces the number of actual I/O operations by reading larger chunks of data at once and storing them in memory.

It makes it simple to handle text input line by line by wrapping around another reader (such as a FileReader or InputStreamReader) and offering methods like readLine() that read a complete line of text.Used to read text files or terminal input line by line.

FileReader

Reads characters straight from a file. Specifically made to read character files, it is a concrete subclass of Reader. It reads the characters one after the other after connecting to a file. Usually used in conjunction with BufferedReader to improve convenience and performance.

InputStreamReader

The purpose of the InputStreamReader is to use a given character encoding (charset) to transform byte streams, or raw bytes, into character streams, or characters.

It serves as a bridge between character-oriented streams (Reader) and byte-oriented streams (InputStream).Commonly used Reading from sources that deliver data in bytes, such as files, network connections, or system input.

By explicitly defining the charset, you can steer clear of platform default encoding problems.

Example
  
    BufferedReader br = new BufferedReader(new FileReader("b.txt"));
    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
  

Note:System.in is a built-in InputStream in Java that represents the standard input stream usually, this means keyboard input from the console.

Writing data

Several classes from the java.io package offer distinct functionalities optimized for different use cases when writing data to files or other output destinations in Java:

BufferedWriter

This class buffers characters before writing them out, allowing it to write characters to an output stream efficiently. It gathers characters in a buffer and writes them in bigger chunks rather than one character at a time. Performance can be greatly enhanced by this buffering, which lowers the number of I/O operations, especially when writing large volumes of text data.

Example


import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
public class AboutBufferedWriter {
    public static void main(String[] args) {
        String filePath = "example1.txt";  // File to write to
        BufferedWriter writer = new BufferedWriter(new FileWriter(filePath))
            writer.write("Hello.");
            writer.newLine();  // Write a newline
            writer.write("This is another line.");
            // No need to call flush() explicitly because close() will flush
        } 
    }
	
	

FileWriter

A practical method for writing character data straight to a file is to use the FileWriter class. At the filesystem level, it manages file creation and writing. To take advantage of buffering, which improves writing performance and lowers overhead, FileWriter is frequently used in conjunction with BufferedWriter.

Example


import java.io.FileWriter;
import java.io.IOException;
public class AboutFileWriter {
    public static void main(String[] args) {
        String filePath = "example2.txt";
        FileWriter fw = new FileWriter(filePath)
            fw.write("Hello");
            fw.write("\nThis is a new line.");
            // You can write strings or characters directly
        } 
    }

OutputStreamWriter

The OutputStreamWriter class serves as a link between byte and character streams. Before publishing characters to an underlying output stream, it uses a predefined character encoding (charset) to transform them into bytes.

This is particularly helpful when you desire control over the character encoding and need to write text data to an output destination that expects bytes, such a file or network socket.

Example

	  
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.io.IOException;
public class AboutOutputStreamWriter {
    public static void main(String[] args) {
        String filePath = "example3.txt";
        OutputStreamWriter writer = new OutputStreamWriter(new FileOutputStream(filePath), "UTF-8")
            writer.write("Hello");
            writer.write("\nThis text.");
        
    }
}

Java File I/O Class Hierarchy and Relationships

The java.io package's deep class hierarchy serves as the foundation for Java's file input/output (I/O) system, which is intended to offer flexible and effective handling of files and data streams. Selecting the appropriate tools for reading and writing data is made easier by knowing how these classes relate to one another.

Some Java File I/O Class Relationships

public class FileInputStream extends InputStream

You can use this class to read raw bytes from a file. It is a subclass of the abstract InputStream class, which defines fundamental methods for reading byte streams. Use FileInputStream when working directly with binary data from files.

public class FileReader extends InputStreamReader

The FileReader class in Java is used to read character data from files. It is a convenience class for reading text files, as it automatically converts bytes from a file into characters using the platform's default character encoding. FileReader is a subclass of InputStreamReader, which bridges byte streams to character streams.

public class FileOutputStream extends OutputStream

The FileOutputStream class in Java is used to write raw bytes to a file. It is typically used for writing binary data, such as image files, audio files, or any non-text file. This class is a subclass of OutputStream.

public class FileWriter extends OutputStreamWriter

The FileWriter class in Java is used to write character data to files. It simplifies writing text by converting characters into bytes using the platform’s default character encoding. FileWriter is a subclass of OutputStreamWriter.

public class File extends Object

The File class in Java represents file and directory pathnames in an abstract manner. It provides functionality to create, delete, rename, and inspect files or directories, but does not itself read or write file contents.

public abstract class InputStream extends Object

The InputStream class is the abstract superclass for all classes that represent byte input streams in Java. It defines the basic methods for reading raw bytes from input sources such as files, memory, or network connections.

public abstract class OutputStream extends Object

The OutputStream class is the abstract superclass for all classes that represent byte output streams in Java. It provides the basic methods for writing raw bytes to output destinations such as files, memory, or network sockets.

public class BufferedReader extends Reader

The BufferedReader class in Java buffers character input to provide efficient reading of text data, such as characters, arrays, and lines. It wraps around other Reader instances (like FileReader) and reduces the number of I/O operations by reading larger blocks of data at once

public class BufferedWriter extends Writer

The BufferedWriter class in Java buffers character output to improve writing efficiency by minimizing the number of actual write operations to the underlying output stream or writer. It wraps around other Writer instances (like FileWriter) to provide this buffering.

public class DataInputStream extends FilterInputStream implements DataInput

The DataInputStream class allows an application to read primitive Java data types (such as int, float, double, long, short, byte, and boolean) and UTF-8 encoded strings from an underlying input stream in a portable and machine-independent way. It extends FilterInputStream and implements the DataInput interface.

public class DataOutputStrea extends FilterOutputStream implements DataOutput

The DataOutputStream class lets you write primitive Java data types (like int, float, double, long, short, byte, boolean) and UTF-8 encoded strings to an output stream in a portable and machine-independent format. It extends FilterOutputStream and implements the DataOutput interface.

File and FileDialog Classes

A crucial component of Java's java.io package is the File class. Because it offers an abstraction for file and directory pathnames, your software can communicate with files and directories without being reliant on the operating system..

Constructor

To build a new File object that represents a file or directory path in the filesystem, use Java's File(String pathname)constructor. A String containing the path to the file or directory is the only argument this constructor accepts.

Common Methods of File Class

Java's File class has a number of helpful methods for examining the characteristics and status of files or directories. Here are a few that are frequently used:

  • boolean canRead(): This function determines if the program is authorized to read the file or directory that the File object represents.
    If the file is present and readable, it returns true; if not, it returns false.

  • boolean canWrite(): Determines if the program is authorized to write to or edit the file or directory.
    Returns: false otherwise; true if the file is writable and exists.

  • String getName(): This function gives back the name of the file or directory that the File object represents.
    The entire path is not returned; only the name portion is. It returns a String with the name of the file or directory.

FileDialog Class

The java.awt package's FileDialog class provides a graphical user interface that enables users to select files in a manner consistent with the built-in file chooser of their operating system.This implies that the file selection window in your Java program that makes use of FileDialog will seem and function exactly like other file dialogs that the user is accustomed to on their platform, be it Windows, macOS, or Linux.

This class handles file browsing, directory navigation, and file type filtering automatically, making it easier for users to open existing files or specify files to save.

Static Constants

File Dialog class has two main modes of operation: reading (opening files) and writing (saving files).The FileDialog constants enable developers to choose the appropriate mode.

  • FileDialog.LOAD: Allows the user to choose which file to read from by specifying the mode for opening a file
  • FileDialog.SAVE: Indicates the saving mode, giving the user the option to select the location and filename to write to.

Common Constructor

  FileDialog(Frame parent, String title, int mode)
  
      
  • Frame parent: The parent window (or frame) that is the owner of the file dialog is specified by this parameter. In relation to this parent, the file dialog will be modal, which means it will remain on top of the parent window and won't allow interaction with the parent until the dialog is closed. This guarantees appropriate window focus behavior and a seamless user experience.

  • String title: This is the text that shows up in the file dialog window's title bar. With options like "Open File" or "Save As," it helps the user understand what the window is for.

  • int mode: The dialog's goal is determined by this integer value. One of two predefined constants is accepted by it:

In Java, the FileDialog class is frequently used in conjunction with other input/output (I/O) classes to better manage file operations. These classes allow reading from or writing to a file that has been selected by the user using a FileDialog:

FileWriter and FileReader: Simple character-based file writing and reading features are offered by the FileWriter and FileReader classes. For instance, you can use FileWriter to write text data to the file or FileReader to retrieve text data from it once you have obtained the file path from a FileDialog.
InputStreamReader and OutputStreamWriter: serve as intermediaries between character and byte streams. They make working with text data easier, particularly when working with different encodings, by converting raw bytes to characters (and vice versa). When you want to set character encoding or have additional control over how data is read or written, these can be helpful.
BufferedReader and BufferedWriter: By buffering the input or output, these classes wrap around other readers and writers to increase efficiency. When working with huge files or frequent I/O operations, they improve speed by processing chunks of data rather than reading or writing one character at a time.

Common Methods

  • String getDirectory(): It assists your program in determining which folder contains the selected file or where the user wants to save a new file.

  • String getFile(): This function gives back the file name that the user has chosen. This method could return null if the user closes the dialog or doesn't select a file.
Example →Creating new File with Java

import java.io.File;
public class OneCreateFile {
    public OneCreateFile() {  
       createFile();   //Calling createFile() 
    }
    public static void main(String[] args) {
        OneCreateFile cr = new OneCreateFile();
    }
public void createFile()
{
   try {
            File file = new File("oop.txt");
            if (file.createNewFile()) {
                System.out.println("File Created!");
                System.out.println("Created File Name:"+file.getName());
                System.out.println("Created File can Execute?:"+file.canExecute());
                System.out.println("Created File can Write?:"+file.canWrite());
            } else {
                System.out.println("File aleardy Created!");
                System.out.println("File Information");
                System.out.println("Absolute Path:" + file.getAbsolutePath());
            }
        } catch (Exception e) {
            System.err.println("Exception:" + e.getMessage());
        }
}
}

    

Latest Posts


File Handling in C++

File Handling in C++

LetUsLearn May 28, 2025
Getting Started with Java GUI

Getting Started with Java GUI

LetUsLearn May 28, 2025
Top 9 Web hosting Companies in Ethiopia

Top 9 Web hosting Companies in Ethiopia

LetUsLearn May 28, 2025
Yilma Goshime

I’m committed to providing tailored solutions and always ready to assist if any issue arises.

LetUsLearn
Back to Top