Day 1: Introduction to Java

icon picker
Day 10: File Handling in Java


Welcome to Day 10 of our Java programming journey! Today, we will dive into the world of file handling, an essential topic for any programmer. We will learn how to read and write files, work with file input and output streams, and handle both text and binary files. By the end of this blog, you will have a solid foundation in file handling in Java.
Why File Handling is Required?
File Handling is an integral part of any programming language as file handling enables us to store the output of any particular program in a file and allows us to perform certain operations on it.
In simple words, file handling means reading and writing data to a file.

Reading and Writing Files

Reading Files

Reading files in Java is a common task, whether you are processing user input or working with external data sources. To read a file, we typically follow these steps:
Create a File Object: First, create a File object that represents the file you want to read.
javaCopy code
File file = new File("example.txt");
Create a FileReader: Next, create a FileReader to read the contents of the file.
javaCopy code
FileReader reader = new FileReader(file);
Reading File Content: You can read the file's content character by character, line by line, or using other methods provided by Java's I/O classes.
javaCopy code
int data; while ((data = reader.read()) != -1) { char character = (char) data; // Process the character }
Close the FileReader: Always close the FileReader when you're done to free up system resources.
javaCopy code
reader.close();

// Importing File Class
import java.io.File;

class Day10{
public static void main(String[] args)
{

// File name specified
File obj = new File("myfile.txt");
System.out.println("File Created!");
}
}

Writing Files

Writing files is just as important as reading them. To write data to a file, you can follow these steps:
Create a FileWriter: Create a FileWriter to write data to the file. You can also use BufferedWriter for better performance.
javaCopy code
FileWriter writer = new FileWriter("output.txt");
Write Data: Use the write method of the FileWriter to write data to the file.
javaCopy code
writer.write("Hello, world!");
Flush and Close: After writing data, it's a good practice to flush the writer and then close it.
javaCopy code
writer.flush(); writer.close();

File Input and Output Streams

In addition to character-based file handling, Java also provides byte-based file handling through input and output streams. This is useful for working with binary files.

Reading Binary Files

To read binary files, you can use FileInputStream:
javaCopy code
try (FileInputStream inputStream = new FileInputStream("binary.dat")) {
int data;
while ((data = inputStream.read()) != -1) {
// Process the byte data
}
} catch (IOException e) {
e.printStackTrace();
}

Writing Binary Files

To write binary files, you can use FileOutputStream:
javaCopy code
try (FileOutputStream outputStream = new FileOutputStream("binary.dat")) {
byte[] data = { 0x48, 0x65, 0x6C, 0x6C, 0x6F }; // "Hello" in hexadecimal
outputStream.write(data);
} catch (IOException e) {
e.printStackTrace();
}

Handling Text and Binary Files

Java supports both text and binary file handling. The examples above show how to work with text files using FileReader and FileWriter, and how to work with binary files using FileInputStream and FileOutputStream. Depending on your use case, you may need to choose the appropriate method for handling files.

Create a File

// Import the File class
import java.io.File;

// Import the IOException class to handle errors
import java.io.IOException;

public class day10{
public static void main(String[] args)
{

try {
File Obj = new File("myfile.txt");
//File myObj = new File("C:\\Users\\MyName\\filename.txt");
if (Obj.createNewFile()) {
System.out.println("File created: " + Obj.getName());
}
else {
System.out.println("File already exists.");
}
}
catch (IOException e) {
System.out.println("An error has occurred.");
e.printStackTrace();
}
}
}

Write To a File


import java.io.FileWriter; // Import the FileWriter class
import java.io.IOException; // Import the IOException class to handle errors

public class WriteToFile {
public static void main(String[] args) {
try {
FileWriter myWriter = new FileWriter("filename.txt");
myWriter.write("Files in programing language, Thank you!");
myWriter.close();
System.out.println("Successfully wrote to the file.");
} catch (IOException e) {
System.out.println("An error occurred.");
e.printStackTrace();
}
}
}

Read a File

import java.io.File; // Import the File class
import java.io.FileNotFoundException; // Import this class to handle errors
import java.util.Scanner; // Import the Scanner class to read text files

public class ReadFile {
public static void main(String[] args) {
try {
File myObj = new File("filename.txt");
Scanner myReader = new Scanner(myObj);
while (myReader.hasNextLine()) {
String data = myReader.nextLine();
System.out.println(data);
}
myReader.close();
} catch (FileNotFoundException e) {
System.out.println("An error occurred.");
e.printStackTrace();
}
}
}

Delete a File

import java.io.File; // Import the File class

public class DeleteFile {
public static void main(String[] args) {
File myObj = new File("filename.txt");
if (myObj.delete()) {
System.out.println("Deleted the file: " + myObj.getName());
} else {
System.out.println("Failed to delete the file.");
}
}
}


Exercise Questions

How do you read a text file in Java using FileReader? Provide an example.
Answer: You can read a text file in Java using FileReader as follows:
javaCopy code
try (FileReader reader = new FileReader("example.txt")) { int data; while ((data = reader.read()) != -1) { char character = (char) data; // Process the character } } catch (IOException e) { e.printStackTrace(); }
What is the difference between FileInputStream and FileReader in Java?
Answer: FileInputStream is used for reading binary data from a file, while FileReader is used for reading character data from a file. FileInputStream reads bytes, whereas FileReader reads characters and handles character encoding automatically.
How do you write data to a binary file in Java? Provide an example using FileOutputStream.
Answer: You can write data to a binary file in Java using FileOutputStream as follows:
javaCopy code
try (FileOutputStream outputStream = new FileOutputStream("binary.dat")) { byte[] data = { 0x48, 0x65, 0x6C, 0x6C, 0x6F }; // "Hello" in hexadecimal outputStream.write(data); } catch (IOException e) { e.printStackTrace(); }
Why is it important to close file streams after using them in Java?
Answer: Closing file streams is important to release system resources and ensure that any pending data is written or read correctly. Failure to close streams can result in resource leaks and unexpected behavior in your program.
When should you use text file handling and when should you use binary file handling in Java?
Answer: Use text file handling when you need to work with human-readable text data, such as configuration files or log files. Use binary file handling when you need to work with non-text data, such as images, audio, or serialized objects, where the data format is not meant to be human-readable.
Now that you have a solid understanding of file handling in Java, practice these concepts with various file manipulation tasks to reinforce your knowledge. Happy coding!

Certainly! Here's a complete Java code example that demonstrates reading and writing files using both character-based (FileReader and FileWriter) and byte-based (FileInputStream and FileOutputStream) approaches:
javaCopy code
import java.io.*;

public class FileReadWriteExample {

public static void main(String[] args) {
// Reading and Writing Text Files
readWriteTextFile();

// Reading and Writing Binary Files
readWriteBinaryFile();
}

// Reading and Writing Text Files
private static void readWriteTextFile() {
try {
// Reading a Text File
File inputFile = new File("input.txt");
FileReader reader = new FileReader(inputFile);
BufferedReader bufferedReader = new BufferedReader(reader);

// Writing to a Text File
File outputFile = new File("output.txt");
FileWriter writer = new FileWriter(outputFile);

String line;
while ((line = bufferedReader.readLine()) != null) {
// Process and write the line
writer.write(line + "\n");
}

// Close the reader and writer
bufferedReader.close();
writer.close();

System.out.println("Text file copied successfully.");
} catch (IOException e) {
e.printStackTrace();
}
}

// Reading and Writing Binary Files
private static void readWriteBinaryFile() {
try {
// Reading a Binary File
File binaryInputFile = new File("input.bin");
FileInputStream inputStream = new FileInputStream(binaryInputFile);

// Writing to a Binary File
File binaryOutputFile = new File("output.bin");
FileOutputStream outputStream = new FileOutputStream(binaryOutputFile);

int data;
while ((data = inputStream.read()) != -1) {
// Process and write the byte
outputStream.write(data);
}

// Close the input and output streams
inputStream.close();
outputStream.close();

System.out.println("Binary file copied successfully.");
} catch (IOException e) {
e.printStackTrace();
}
}
}

In this code, we have two methods: readWriteTextFile() for reading and writing text files and readWriteBinaryFile() for reading and writing binary files. Make sure to place the input.txt and input.bin files in the same directory as this Java class before running the code. After execution, you will find the copied text in "output.txt" and the copied binary data in "output.bin" in the same directory
Want to print your doc?
This is not the way.
Try clicking the ⋯ next to your doc name or using a keyboard shortcut (
CtrlP
) instead.