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.");
}
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.