File comparer Learn programming Java



Lesson:

File Management


Exercise:

File comparer


Objetive:

Create a java program to tell if two files (of any kind) are identical (have the same content).


Code:

package FileComparer;
import java.util.*;

public class Main
{
	public static void main(String[] args)
	{
		boolean equal = true;

		FileStream myFile1;
		byte[] dataFile1;
		FileStream myFile2;
		byte[] dataFile2;

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

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

		if ((!(new java.io.File(fileName1)).isFile()) || (!(new java.io.File(fileName2)).isFile()))
		{
			System.out.println("The file 1 or file 2 not exists!!!");
			return;
		}

		try
		{
			myFile1 = File.OpenRead(fileName1);
			dataFile1 = new byte[myFile1.getLength()];
			myFile1.Read(dataFile1, 0, (int)myFile1.getLength());
			myFile1.Close();

			myFile2 = File.OpenRead(fileName2);
			dataFile2 = new byte[myFile2.getLength()];
			myFile2.Read(dataFile2, 0, (int)myFile2.getLength());
			myFile2.Close();

			if (myFile1.getLength() == myFile2.getLength())
			{
				for (int i = 0; i < dataFile1.length; i++)
				{
					if (dataFile1[i] != dataFile2[i])
					{
						equal = false;
					}
					else
					{
						equal = false;
					}
				}
			}

			if (equal)
			{
				System.out.printf("The %1$s is equal %2$s" + "\r\n", fileName1, fileName2);
			}
			else
			{
				System.out.printf("The %1$s not is equal %2$s" + "\r\n", fileName1, fileName2);
			}

			new Scanner(System.in).nextLine();
		}
		catch (RuntimeException e)
		{
			System.out.printf("Error: %1$s!!!" + "\r\n", e.getMessage());
		}
	}
}



Juan A. Ripoll - Systems Tutorials and Programming Courses ©  All rights reserved.  Legal Conditions.