Invert binary file V2 Learn programming Java

Lesson:

File Management


Exercise:

Invert binary file V2


Objetive:

Create a program to "invert" a file using a "FileStream". The program should create a file with the same name ending in ".inv" and containing the same bytes as the original file but in reverse order. The first byte of the resulting file should be the last byte of the original file, the second byte should be the penultimate, and so on, until the last byte of the original file, which should appear in the first position of the resulting file.

Please deliver only the ".cs" file, which should contain a comment with your name.


Code:

import java.util.*;
public class Main
{
	public static void main(String[] args)
	{
		String fileName;

		System.out.print("Enter the name of file to convert: ");
		fileName = new Scanner(System.in).nextLine();

		java.io.FileInputStream myFileReader = File.OpenRead(fileName);

		long size = myFileReader.getLength();

		byte[] data = new byte[size];
		myFileReader.read(data, 0, (int)size);
		myFileReader.close();

		java.io.FileOutputStream myFileWriter = File.Create(fileName + ".inv");

		for (long i = size - 1; i >= 0; i--)
		{
			myFileWriter.write(data[i]);
		}

		myFileWriter.close();
	}
}

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