Encrypt a BMP file Learn programming Java

Lesson:

File Management


Exercise:

Encrypt a BMP file 8


Objetive:

Create a program to encrypt/decrypt a BMP image file, by changing the "BM" mark in the first two bytes with MB and vice versa.

Use the advanced FileStream constructor to allow simultaneous reading and writing.


Code:

package Bmp;
import java.util.*;

public class Main
{
	public static void main(String[] args)
	{
		FileStream myFile;

		System.out.print("Enter the name of file: ");
		String fileName = new Scanner(System.in).nextLine();

		if (!(new java.io.File(fileName)).isFile())
		{
			System.out.println("The file not exists!!!");
			return;
		}

		try
		{
			myFile = File.Open(fileName, FileMode.Open, FileAccess.ReadWrite);
			
            byte b1 = (byte)myFile.ReadByte();
			byte b2 = (byte)myFile.ReadByte();

			if (((char)b1 != 'B') || ((char)b2 != 'M'))
			{
				System.out.println("This File is NOT a BMP file");
			}
			else
			{
				myFile.Seek(0, SeekOrigin.Begin);
				myFile.WriteByte((byte)'M');
				myFile.WriteByte((byte)'B');
			}
			myFile.Close();
		}
		catch (RuntimeException e)
		{
			System.out.printf("Error: %1$s!!!" + "\r\n", e.message());
		}
	}
}