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
Lab Manual of Physics
Category: Practical FilesJuly 17, 2022
Computer Applications Notes Unit 2
Category: NotesJuly 16, 2022
Applied Maths Solved Question Papers Akash 2013-2016
Category: Question PapersJuly 16, 2022
Industrial Management Akash 2015
Category: Question PapersJuly 16, 2022
Applied Chemistry Viva Questions PDF
Category: Practical FilesJuly 16, 2022
BBA FAA Notes Unit 3
Category: NotesJuly 16, 2022
IPU GST Notes Unit 2
Category: NotesJuly 17, 2022
Digital Marketing Notes IPU Unit 4
Category: NotesJuly 17, 2022
Java File Handling
Category: NotesJuly 16, 2022
Unit 3 Water Photocopied Notes
Category: NotesJuly 16, 2022