Java Input/Output (I/O)

Working with Files and Streams:

Java Input/Output (I/O) is a crucial aspect of Java programming, enabling seamless data handling from various sources. It involves working with files and streams to read and write data efficiently.

Example of Working with Streams:

try (FileInputStream inputStream = new FileInputStream(“input.txt”);
FileOutputStream outputStream = new FileOutputStream(“output.txt”)) {

int data;
while ((data = inputStream.read()) != -1) {
outputStream.write(data);
}

} catch (IOException e) {
e.printStackTrace();
}

Reading and Writing Data to Files:

Java I/O provides classes like FileReader, FileWriter, BufferedReader, and BufferedWriter to simplify reading and writing data to files. These classes offer convenient methods for efficient data handling.

Example of Reading and Writing Data:

try (BufferedReader reader = new BufferedReader(new FileReader(“input.txt”));
BufferedWriter writer = new BufferedWriter(new FileWriter(“output.txt”))) {

String line;
while ((line = reader.readLine()) != null) {
writer.write(line);
writer.newLine();
}

} catch (IOException e) {
e.printStackTrace();
}

Serialization and Deserialization:

Java supports serialization, allowing objects to be converted into a byte stream for storage or transmission. Deserialization reverses this process, recreating objects from the byte stream.

Example of Serialization and Deserialization:

import java.io.*;

class Person implements Serializable {
private String name;
private int age;

public Person(String name, int age) {
this.name = name;
this.age = age;
}

// Getters and setters
}

// Serialization
try (FileOutputStream fileOut = new FileOutputStream(“person.ser”);
ObjectOutputStream out = new ObjectOutputStream(fileOut)) {

Person person = new Person(“Alice”, 30);
out.writeObject(person);

} catch (IOException e) {
e.printStackTrace();
}

// Deserialization
try (FileInputStream fileIn = new FileInputStream(“person.ser”);
ObjectInputStream in = new ObjectInputStream(fileIn)) {

Person person = (Person) in.readObject();
System.out.println(“Name: ” + person.getName() + “, Age: ” + person.getAge());

} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
}

Conclusion:

Java Input/Output (I/O) forms the backbone of data handling in Java applications. By mastering file and stream handling, reading and writing data, and understanding serialization and deserialization, you can build robust and efficient solutions. I/O empowers Java developers to interact with external resources and persist data seamlessly. Embrace the power of Java I/O, and unleash the true potential of data manipulation in your Java projects!

Leave a Comment