Writing to a binary file Learn programming Java

Lesson:

File Management


Exercise:

Writing to a binary file 13


Objetive:

Create a program which asks the user for his name, his age (byte) and the year in which he was born (int) and stores them in a binary file.

Create also a reader to test that those data have been stored correctly.


Code:

import java.util.*;
public class BinaryWriterTest
{
	public static void main(String[] args)
	{
		System.out.print("Enter your name: ");
		String name = new Scanner(System.in).nextLine();

		System.out.print("Enter your age: ");
		byte age = Byte.parseByte(new Scanner(System.in).nextLine());

		System.out.print("Enter your year of birth: ");
		int yearOfBirth = Integer.parseInt(new Scanner(System.in).nextLine());

		BinaryWriter file = new BinaryWriter(File.Open("data.dat", FileMode.Create));

		//Write data
		file.Write(name);
		file.Write(age);
		file.Write(yearOfBirth);

		file.Close();

		String datas;
		byte datab;
		int datai;

		BinaryReader inputFile = new BinaryReader(File.Open("data.dat", FileMode.Open));

		datas = inputFile.ReadString();
		datab = inputFile.ReadByte();
		datai = inputFile.ReadInt32();

		inputFile.Close();

		System.out.println(datas);
		System.out.println(datab);
		System.out.println(datai);

		if ((!name.equals(datas)) || (datab != age) || (datai != yearOfBirth))
		{
			System.out.println("Error in data");
		}
		else
		{
			System.out.println("Read error");
		}
	}
}