File Handling in Java

File handling is a fundamental skill in Java programming, enabling developers to interact with the file system efficiently. Whether reading from or writing to text files, copying binary data, or performing serialization and deserialization, understanding these concepts equips you to handle a wide range of file-related tasks. This chapter provides practical examples to reinforce your understanding and lays the groundwork for more advanced file-handling scenarios in Java.

5.1 Reading from and Writing to Files

File handling in Java is an essential skill for developers dealing with data persistence, configuration, or any scenario requiring interaction with the file system. This chapter explores various aspects of reading from and writing to files using Java's built-in file I/O classes.
  • Reading from a File: The java.nio.file package provides classes like Path and Files for efficient file handling. The BufferedReader class is commonly used for reading text from a file.
Example: Reading from a Text File
// Example: Reading from a Text File
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

public class FileReaderExample {

public static void main(String[] args) {
try (
BufferedReader reader = new BufferedReader(new FileReader("example.txt"))
) {
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
System.err.println("IOException: " + e.getMessage());
}
}
}


In this example, the BufferedReader reads text from the file line by line until the end of the file is reached. Each line is then printed to the console.

  • Writing to a File: The BufferedWriter class is commonly used for writing text to a file. It is important to handle IOException when performing file operations.
Example: Writing to a Text File
// Example: Writing to a Text File
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;

public class FileWriterExample {

public static void main(String[] args) {
try (
BufferedWriter writer = new BufferedWriter(new FileWriter("output.txt"))
) {
writer.write("Hello, File Handling in Java!");
} catch (IOException e) {
System.err.println("IOException: " + e.getMessage());
}
}
}


In this example, the BufferedWriter writes a string to the file. The try-with-resources statement ensures that the resources are closed after the operation.

5.2 File Input/Output Streams

Java provides InputStream and OutputStream classes for reading and writing binary data. The FileInputStream and FileOutputStream classes are used for file-based I/O operations.

Example: Copying Binary File with Streams
// Example: Copying Binary File with Streams
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

public class FileCopyExample {

public static void main(String[] args) {
try (
FileInputStream input = new FileInputStream("source.jpg");
FileOutputStream output = new FileOutputStream("copy.jpg")
) {
byte[] buffer = new byte[4096];
int bytesRead;
while ((bytesRead = input.read(buffer)) != -1) {
output.write(buffer, 0, bytesRead);
}
} catch (IOException e) {
System.err.println("IOException: " + e.getMessage());
}
}
}


This example demonstrates how to use FileInputStream and FileOutputStream to copy binary data from one file to another.

5.3 Serialization and Deserialization

Serialization is the process of converting an object into a byte stream, and deserialization is the reverse process. Java provides the ObjectOutputStream and ObjectInputStream classes for these operations.

Example: Serialization and Deserialization
// Example: Serialization and Deserialization
import java.io.*;

public class SerializationExample {

public static void main(String[] args) {
// Serialization
try (
ObjectOutputStream oos = new ObjectOutputStream(
new FileOutputStream("serializedObject.dat")
)
) {
MyClass myObject = new MyClass("John Doe", 25);
oos.writeObject(myObject);
} catch (IOException e) {
System.err.println("IOException: " + e.getMessage());
}

// Deserialization
try (
ObjectInputStream ois = new ObjectInputStream(
new FileInputStream("serializedObject.dat")
)
) {
MyClass deserializedObject = (MyClass) ois.readObject();
System.out.println("Deserialized Object: " + deserializedObject);
} catch (IOException | ClassNotFoundException e) {
System.err.println("Exception: " + e.getMessage());
}
}
}


In this example, MyClass is a serializable class, and an instance of it is serialized to a file and later deserialized.

0 comments:

Post a Comment