Java Program Read and Write to a Binary File example
read_write_binary_file.txt
File size: 1.46 KB
File content type: text/plain
Category: Practical Files
Subject: Java Programming
import java.io.*;
public class BinaryFileExample {
public static void main(String[] args) throws Exception {
// file extension can be anything doesn't matter
FileOutputStream fileOutputStream = new FileOutputStream("test.obj");
DataOutputStream out = new DataOutputStream(fileOutputStream);
// generally custom objects are stored in binary format like image, video, game data etc
// decide how data need to be stored in binary file
// we will store a list of 3 student info, Name and then Roll Number
out.writeUTF("Hamid");
out.writeInt(1);
out.writeUTF("Rohan");
out.writeInt(2);
out.writeUTF("Shubham");
out.writeInt(3);
out.close(); // close the stream
// Now reading from same file we created, We should know the format in which the binary file was created
// first is name then is roll number, if we try first roll number then name we get error
FileInputStream fileInputStream = new FileInputStream("test.obj");
DataInputStream in = new DataInputStream(fileInputStream);
try {
while (true) {
String name = in.readUTF();
int rollNumber = in.readInt();
System.out.println("Name = " + name + " Roll Number = " + rollNumber);
}
} catch (EOFException e) {
System.out.println("Finished reading file");
}
in.close();
}
}
Read Binary File in Java
Write Binary File in Java Example
Last Updated: July 16, 2022
Related
IPU Entrepreneurship Development Notes Unit 2
Category: NotesJuly 17, 2022
Physics Lab Manual Printed
Category: Practical FilesJuly 16, 2022
Digital Marketing Notes PDF
Category: NotesJuly 17, 2022
IPU Business Communication Notes Unit 4
Category: NotesJuly 17, 2022
IPU Project Management Notes Unit 2 PDF
Category: NotesJuly 17, 2022
BBA Entrepreneurship Development Notes Unit 3
Category: NotesJuly 17, 2022
Business Communication Notes Unit 3
Category: NotesJuly 17, 2022
Power Electronics Complete Notes
Category: NotesJuly 17, 2022
BL Thareja Volume 2 PDF
Category: eBooksJuly 16, 2022
IPU Indian Economy Notes Unit 4
Category: NotesJuly 17, 2022