File splitter Learn programming Java

Lesson:

File Management


Exercise:

File splitter


Objetive:

Create a program to split a file (of any kind) into pieces of a certain size. It must receive the name of the file and the size as parameters. For example, it can be used by typing:

split myFile.exe 2000

If the file "myFile.exe" is 4500 bytes long, that command would produce a file named "myFile.exe.001" that is 2000 bytes long, another file named "myFile.exe.002" that is also 2000 bytes long, and a third file named "myFile.exe.003" that is 500 bytes long.


Code:

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

		java.io.FileInputStream myFile;
		java.io.FileOutputStream myNewFile;

		String nameFile;
		int BUFFER_SIZE;
		int amountRead;
		int count = 1;

		if (args.length == 2)
		{
			nameFile = args[0];
			BUFFER_SIZE = Integer.parseInt(args[1]);

			byte[] data = new byte[BUFFER_SIZE];

			try
			{
				myFile = File.OpenRead(nameFile);
				do
				{
					amountRead = myFile.read(data, 0, BUFFER_SIZE);
					myNewFile = File.Create(nameFile + (new Integer(count)).toString("000"));
					myNewFile.write(data, 0, amountRead);
					count++;
					myNewFile.close();

				} while (amountRead == BUFFER_SIZE);
				myFile.close();
			}
			catch (RuntimeException fileError)
			{
				System.out.println("ERROR has ocurred while executing: " + fileError.getMessage());
			}
		}
		else
		{
			System.out.println("The parameters are incorrects");
			System.out.println("usage: splitfile namefile sizeinbytes");
		}
	}
}

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