writing-and-reading-data-in-file-using-DataInputStream-and-DataOutputStream-in-java-with-examples
admin
Java file operations DataInputStream vs DataOutputStream
Updated: 06/Feb/2025 by Computer Hope
Efficient file handling is crucial for Java developers working with structured data storage. The DataInputStream and DataOutputStream classes allow reading and writing primitive data types efficiently. This tutorial provides a detailed guide on how to write and read data from a file using Java.
The DataOutputStream class provides methods to write primitive data types to a file.
import java.io.*;
import java.util.*;
class Emp {
private int age;
private String name;
private double sal;
public void get() {
Scanner kb = new Scanner(System.in);
System.out.println("Enter age, name, and salary:");
age = kb.nextInt();
name = kb.next();
sal = kb.nextDouble();
}
public void show() {
System.out.println("Age: " + age);
System.out.println("Name: " + name);
System.out.println("Salary: " + sal);
}
public void writeInFile() {
try (DataOutputStream dout = new DataOutputStream(new FileOutputStream("D:/DeveloperFile.dat"))) {
dout.writeInt(age);
dout.writeUTF(name);
dout.writeDouble(sal);
} catch (Exception ex) {
System.out.println("Error in writing: " + ex);
}
}
}
Enter age, name, and salary:
25 John 55000.50
Data written successfully.
The DataInputStream class allows reading primitive data types from a file in the same order they were written.
class ExampleReadWrite {
public static void main(String args[]) {
Emp E = new Emp();
E.get();
E.writeInFile();
Emp F = new Emp();
F.readFromFile();
F.show();
}
}
Age: 25
Name: John
Salary: 55000.50
By using DataInputStream and DataOutputStream, developers can:
BufferedReader or PrintWriter.
DataOutputStream and DataInputStream are essential for structured binary data handling in Java. By following best practices, developers can ensure efficient file management and data integrity.