File copier Learn programming Java

Lesson:

File Management


Exercise:

File copier


Objetive:

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

mycopy file.txt e:\file2.txt

The program should handle cases where the source file does not exist, and it should warn the user (but not overwrite) if the destination file already 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();
	}
}

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