ArrayList duplicate a text file Learn programming Java

Lesson:

Dynamic Memory Management


Exercise:

ArrayList duplicate a text file


Objetive:

Create a program that reads from a text file and stores it to another text file by reversing the order of lines.

For example, an input text file like:

yesterday Real Madrid
won against
Barcelona FC

will be stored in an output text file like:

Barcelona FC
won against
yesterday Real Madrid


Code:

package TextFileInvert;
import java.util.*;
public class Main
{
	static void main(String[] args)
	{
		System.out.print("Introduce el nombre del fichero: ");
		String nombreArchivo = new Scanner(System.in).nextLine();

		if (!(new java.io.File(nombreArchivo)).isFile())
		{
			System.out.print("El archivo no existe!");
			return;
		}

		try
		{
			java.io.FileReader miArchivo;
		java.io.BufferedReader miArchivoBufferedReader = new java.io.BufferedReader(miArchivo);
			miArchivo = new java.io.FileReader(nombreArchivo);
			String line;

			ArrayList miLista = new ArrayList();

			do
			{
				line = miArchivoBufferedReader.readLine();
				if (line != null)
				{
					miLista.add(line);
				}
			} while (line != null);

			miArchivo.close();

			java.io.FileWriter miArchivoAlReves = new java.io.FileWriter(nombreArchivo + "-reverse.txt");

			int tamanyoArchivo = miLista.size();
			for (int i = tamanyoArchivo - 1; i >= 0; i--)
			{
				miArchivoAlReves.write(String.valueOf(miLista.get(i)) + System.lineSeparator());
			}

			miArchivoAlReves.close();

		}
		catch (RuntimeException e)
		{
			System.out.println("Error, " + e.getMessage());
		}
		new Scanner(System.in).nextLine();
	}
}

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