Dump Learn programming with Java exercises

Lesson:

File Management


Exercise:

Dump 72


Objetive:

Create a "dump" utility: an hex viewer, to display the contents of a file, 16 bytes in each row, 24 files in each screen (and then it must pause before displaying the next 24 rows).

In each row, the 16 bytes must be displayed first in Hex and then as characters (the bytes under 32 must be displayed as a dot, instead of the corresponding non printable character).

Look for "hex editor" in Google Images, if you want to see and example of the expected appearance.


Code:

import java.util.*;
public class Main
{
	public static void main(String[] args)
	{
		java.io.FileInputStream file;
		final int SIZE_BUFFER = 16;

		String name = new Scanner(System.in).nextLine();

		try
		{
			file = File.OpenRead(name);
			byte[] data = new byte[SIZE_BUFFER];

			int amount;
			int c = 0;

			String line;
			do
			{
				System.out.print(ToHex(file.Position, 8));
				System.out.print("  ");


				amount = file.read(data, 0, SIZE_BUFFER);

				for (int i = 0; i < amount; i++)
				{
					System.out.print(ToHex(data[i], 2) + " ");

					if (data[i] < 32)
					{
						line += ".";
					}
					else
					{
						line += (char)data[i];
					}
				}


				if (amount < SIZE_BUFFER)
				{
					for (int i = amount; i < SIZE_BUFFER; i++)
					{
						System.out.print("   ");
					}
				}

				System.out.println(line);
				line = "";

				c++;
				if (c == 24)
				{
					new Scanner(System.in).nextLine();
					c = 0;
				}
			} while (amount == SIZE_BUFFER);

			file.close();
		}
		catch (RuntimeException e)
		{
			System.out.println("Error");
		}
	}

	public static String ToHex(int n, int digits)
	{
		String hex = String.valueOf(n, 16);
		while (hex.length() < digits)
		{
			hex = "0" + hex;
		}
		return hex;
	}
}