Exercises Java with Examples-
Practice Exercises Java 4,5 5 302940

ArrayList duplicate a text file - Practice Exercises Java


Lesson 11:

Dynamic memory management


Exercise 11.6:

ArrayList duplicate a text file


Objetive:

Create a program that reads from a text file and stores to another text file inverting the lines.

So, an input text file like:

ayer el Madrid
le ganó
al Barcelona

will be stored in an output text file like:

al Barcelona
le ganó
ayer el Madrid


Source 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();
	}
}
Exercisey 11.6

Share Now:


Google Ads





Privacy Policy:



Google uses associated advertising companies to serve ads when it visits our website. These companies may use the information they obtain from your visits to this and other websites (not including your name, address, email address, or phone number) to provide you with announcements about products and services that interest you. If you would like to learn more about this practice and know your options to prevent these companies from using this information. Click in... Privacy and Terms of Google.

Cookies

This site uses Google cookies to provide its services, to personalize advertisements and to analyze traffic. Google receives information about your use of this website. More information in... Privacy and Terms of Google.