Introduction
Handling file input and output operations is a fundamental task in Java programming, often facilitated by the FileOutputStream and FileInputStream classes. These classes, part of the java.io package, provide a straightforward way to read from and write to files. FileOutputStream is used to write binary data to a file, creating the file if it does not exist and overwriting it if it does. On the other hand, FileInputStream is used to read binary data from a file. Together, they allow developers to manage file operations efficiently, supporting tasks such as saving user data, reading configuration files, or processing binary data. Understanding how to utilize these classes is essential for effective file management in Java applications.
Reading/Writing Bytes
Java I/O system provides a number of classes that can handle 8-bit bytes. The two commonly used classes for handling bytes are FileInputStream and FileOutputStream classes.
The program below illustrates how FileOutputStream class is used to write bytes for a file. The program writes the names of some cities stored in a byte array to a new file named “abcd.txt”. we can verify the contents of the file by using the command.
type abcd.txt
Source Code: Writing Bytes to a file
import java.io.*;
class WriteBytes {
public static void main(String args[]) {
byte cities[] = {'G', 'H', 'A', 'Z', 'I', 'A', 'B', 'A', 'D', '\n',
'M', 'O', 'D', 'I', 'N', 'A', 'G', 'A', 'R', '\n',
'D', 'E', 'L', 'H', 'I', '\n'};
FileOutputStream outFile = null;
try {
outFile = new FileOutputStream("abcd.txt");
outFile.write(cities);
outFile.close();
} catch (IOException ios) {
System.out.println(ios);
System.exit(-1);
}
}
}
Output
This code demonstrates how to write a sequence of bytes to a file using the FileOutputStream class. The program defines a class WriteBytes with a main method that initializes a byte array of cities containing the names of three cities ('GHAZIABAD', 'MODINAGAR', and 'DELHI'), each followed by a newline character (\n). A FileOutputStream object named outFile is declared and initialized to null. Within a try block, the FileOutputStream is instantiated to create or overwrite a file named "abcd.txt". The write method of FileOutputStream is then used to write the byte array cities to the file. After writing, the close method is called to release the file resource. If an IOException occurs during this process, it is caught by the catch block, which prints the exception details and exits the program with a status of -1, indicating an error. This program effectively demonstrates basic file writing operations in Java, including error handling for I/O operations.
The following code shows how FileInputStream class is used for reading bytes from a file. The program reads an existing file and displays its bytes on the screen. Remember, before we run this program, we must first create a file for it to read. We may use this program to read the file “abcd.txt” created in the above program.
Source Code: Reading bytes from a file
import java.io.*;
class ReadBytes {
public static void main(String args[]) {
FileInputStream infile = null;
int b;
try {
infile = new FileInputStream(args[0]);
while ((b = infile.read()) != -1) {
System.out.print((char) b);
}
infile.close();
} catch (IOException ios) {
System.out.println(ios);
}
}
}
Output
This code demonstrates how to read bytes from a file using the FileInputStream class. The ReadBytes class contains a main method that accepts a file path as a command-line argument (args[0]). It declares a FileInputStream object infile and initializes it to null. Within a try block, infile is instantiated with the file path specified by the command-line argument. The program then enters a while loop, where it reads bytes from the file one at a time using the read method. Each byte read is cast to a char and printed to the console. The loop continues until the read returns -1, indicating the end of the file. After reading all the bytes, the close method is called to release the file resource. If an IOException occurs during these operations, it is caught by the catch block, which prints the exception details. This program effectively demonstrates how to handle file reading operations and manage resources in Java.
Another Example
The following code illustrates the uses of FileInputStream and FileOutputStream classes to copy files. We need to provide a source filename for reading and a target filename for writing. In this example code, we have supplied file names directly to the constructors while creating a file stream. We may also supply them as command-line arguments. Note that the file ashish.txt already exists and contains the following text.
Ashish Bhatnagar has extensive experience in technology and business management.
He is known for his expertise in driving digital transformation and innovation.
Ashish Bhatnagar has successfully led numerous high-impact projects, demonstrating strong project management and strategic planning skills.
His commitment to excellence and leadership has earned him significant recognition in the technology sector.
Source Code: Copying bytes from one file to another
import java.io.*;
class CopyBytes {
public static void main(String args[]) {
FileInputStream infile = null;
FileOutputStream outfile = null;
byte byteRead;
try {
infile = new FileInputStream("ashish.txt");
outfile = new FileOutputStream("ashish1.txt");
do {
byteRead = (byte) infile.read();
outfile.write(byteRead);
} while (byteRead != -1);
} catch (FileNotFoundException e) {
System.out.println("File Not Found");
} catch (IOException e) {
System.out.println(e.getMessage());
} finally {
try {
if (infile != null) infile.close();
if (outfile != null) outfile.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
Output
This code copies the contents of a file named ashish.txt to another file named ashish1.txt using FileInputStream and FileOutputStream. It initializes the input and output streams, reads bytes from the source file one by one in a do-while loop, and writes each byte to the destination file. The loop continues until the end of the file is reached, which is indicated by infile.read() returning -1. Error handling is implemented to catch FileNotFoundException and IOException, providing appropriate messages if issues occur. The final block attempts to close both streams to free resources, though this might not always execute if the streams are not successfully opened. This code effectively demonstrates basic file copying, though it could be improved by using try-with-resources for automatic resource management and adjusting the loop to handle the end-of-file condition more robustly.
Summary
Managing input and output files in Java using FileOutputStream and FileInputStream involves reading from and writing to files in a straightforward manner. FileOutputStream allows you to write binary data to a file, creating or overwriting the file as needed, while FileInputStream enables reading binary data from a file. By employing these classes, developers can handle various file operations, such as saving data, processing files, and reading content. Proper handling of these streams includes managing exceptions to handle potential I/O errors and ensuring resources are closed after operations are completed. Although basic file I/O operations are effectively managed with these classes, utilizing try-with-resources for automatic resource management can simplify code and improve reliability.