File copier Learn programming Java

Lesson:

File Management


Exercise:

File copier 65


Objetive:

Create a program to copy a source file into a destination file. You must use FileStream and a block size of 512 Kb. An example of use might be:

mycopy file.txt e:\file2.txt

It must behave correctly if the source file does not exist and it must warn (but not overwrite it) if the destination file exists


Code:

public class Main
{
    public static void main(String[] args)
	{
		final int BUFFER_SIZE = 512 * 1024;

		byte[] data = new byte[BUFFER_SIZE];

		java.io.FileInputStream inFile = File.OpenRead("1.exe");
		java.io.FileOutputStream outFile = File.Create("1-copy.exe");

		int amountRead;

		do
		{
			amountRead = inFile.read(data, 0, BUFFER_SIZE);
			outFile.write(data, 0, amountRead);
		} while (amountRead == BUFFER_SIZE);

		inFile.close();
		outFile.close();
	}
}