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
BBA Computer Applications Notes Unit 4
Category: NotesJuly 16, 2022
IPU Quantitative Techniques Notes PDF Unit 3
Category: NotesJuly 17, 2022
Computer Applications Notes Unit 2
Category: NotesJuly 16, 2022
[DCN] Data Communication Networks Aakash 2016 - 2017
Category: Question PapersJuly 17, 2022
[WEB] Web Engineering Formatted Practical File
Category: Practical FilesJuly 16, 2022
BBA Project Management Notes Unit 3
Category: NotesJuly 17, 2022
Lasers Notes
Category: NotesJuly 16, 2022
Java Program to check if a number is prime
Category: Practical FilesJuly 16, 2022
SNT Unit 2
Category: NotesJuly 17, 2022
Income Tax Notes Unit 4
Category: NotesJuly 17, 2022