π Top 15 Udemy Courses (80-90% Discount): My Udemy Courses - Ramesh Fadatare — All my Udemy courses are real-time and project oriented courses.
▶️ Subscribe to My YouTube Channel (178K+ subscribers): Java Guides on YouTube
▶️ For AI, ChatGPT, Web, Tech, and Generative AI, subscribe to another channel: Ramesh Fadatare on YouTube
Reading a file in Java can be accomplished using various classes from the java.io package. One such class is DataInputStream, which allows an application to read primitive data types from an underlying input stream in a machine-independent way. This blog post will guide you through the process of reading a file using DataInputStream.
Table of Contents
- Introduction
- Prerequisites
- Using
DataInputStreamto Read a File - Complete Example
- Conclusion
Introduction
DataInputStream is a class in the java.io package that lets an application read Java primitive data types from an underlying input stream in a machine-independent way. It is particularly useful when reading data that was written using a DataOutputStream. This tutorial will demonstrate how to use DataInputStream to read various data types from a file.
Prerequisites
Before you start, ensure you have the following:
- A basic understanding of Java programming
- A Java development environment (JDK and an IDE like IntelliJ IDEA or Eclipse)
Using DataInputStream to Read a File
To read a file using DataInputStream, you will:
- Create a
FileInputStreamto read the file. - Wrap the
FileInputStreamwith aDataInputStream. - Read the data using the
DataInputStream. - Close the streams to release system resources.
Example
The following example demonstrates how to read a file using DataInputStream.
Step 1: Writing Data to a File
First, let's write some data to a file using DataOutputStream.
import java.io.DataOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
public class WriteDataToFile {
public static void main(String[] args) {
String fileName = "datafile.dat";
try (FileOutputStream fos = new FileOutputStream(fileName);
DataOutputStream dos = new DataOutputStream(fos)) {
dos.writeUTF("Hello, World!");
dos.writeInt(123);
dos.writeDouble(45.67);
System.out.println("Data has been written to " + fileName);
} catch (IOException e) {
e.printStackTrace();
}
}
}
Explanation:
- A
FileOutputStreamis created to write to a file nameddatafile.dat. - A
DataOutputStreamis created to write data types to theFileOutputStream. - The
writeUTF,writeInt, andwriteDoublemethods are used to write aString, anint, and adoubleto the file. - The
try-with-resourcesstatement ensures that the streams are closed automatically.
Step 2: Reading Data from a File
Now, let's read the data from the file using DataInputStream.
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.IOException;
public class ReadDataFromFile {
public static void main(String[] args) {
String fileName = "datafile.dat";
try (FileInputStream fis = new FileInputStream(fileName);
DataInputStream dis = new DataInputStream(fis)) {
String str = dis.readUTF();
int intValue = dis.readInt();
double doubleValue = dis.readDouble();
System.out.println("Read String: " + str);
System.out.println("Read int: " + intValue);
System.out.println("Read double: " + doubleValue);
} catch (IOException e) {
e.printStackTrace();
}
}
}
Explanation:
- A
FileInputStreamis created to read the file nameddatafile.dat. - A
DataInputStreamis created to read data types from theFileInputStream. - The
readUTF,readInt, andreadDoublemethods are used to read aString, anint, and adoublefrom the file. - The
try-with-resourcesstatement ensures that the streams are closed automatically.
Complete Example
Here is the complete example, including both writing to and reading from the file.
WriteDataToFile.java
import java.io.DataOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
public class WriteDataToFile {
public static void main(String[] args) {
String fileName = "datafile.dat";
try (FileOutputStream fos = new FileOutputStream(fileName);
DataOutputStream dos = new DataOutputStream(fos)) {
dos.writeUTF("Hello, World!");
dos.writeInt(123);
dos.writeDouble(45.67);
System.out.println("Data has been written to " + fileName);
} catch (IOException e) {
e.printStackTrace();
}
}
}
ReadDataFromFile.java
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.IOException;
public class ReadDataFromFile {
public static void main(String[] args) {
String fileName = "datafile.dat";
try (FileInputStream fis = new FileInputStream(fileName);
DataInputStream dis = new DataInputStream(fis)) {
String str = dis.readUTF();
int intValue = dis.readInt();
double doubleValue = dis.readDouble();
System.out.println("Read String: " + str);
System.out.println("Read int: " + intValue);
System.out.println("Read double: " + doubleValue);
} catch (IOException e) {
e.printStackTrace();
}
}
}
Conclusion
Reading a file in Java using DataInputStream is an efficient way to handle binary data and primitive data types. By using the DataInputStream, you can read data types that were written using a DataOutputStream. The examples provided demonstrate how to write and read data types to and from a file, making it easier to manage binary data in your Java applications.
Feel free to modify and experiment with the code examples provided in this tutorial to suit your specific needs. Happy coding!
My Top and Bestseller Udemy Courses. The sale is going on with a 70 - 80% discount. The discount coupon has been added to each course below:
Build REST APIs with Spring Boot 4, Spring Security 7, and JWT
[NEW] Learn Apache Maven with IntelliJ IDEA and Java 25
ChatGPT + Generative AI + Prompt Engineering for Beginners
Spring 7 and Spring Boot 4 for Beginners (Includes 8 Projects)
Available in Udemy for Business
Building Real-Time REST APIs with Spring Boot - Blog App
Available in Udemy for Business
Building Microservices with Spring Boot and Spring Cloud
Available in Udemy for Business
Java Full-Stack Developer Course with Spring Boot and React JS
Available in Udemy for Business
Build 5 Spring Boot Projects with Java: Line-by-Line Coding
Testing Spring Boot Application with JUnit and Mockito
Available in Udemy for Business
Spring Boot Thymeleaf Real-Time Web Application - Blog App
Available in Udemy for Business
Master Spring Data JPA with Hibernate
Available in Udemy for Business
Spring Boot + Apache Kafka Course - The Practical Guide
Available in Udemy for Business
Comments
Post a Comment
Leave Comment