Exercise
Mix and sort files
Objetive
Create a program that reads the contents of two different files, merges them, and sorts them alphabetically. For example, if the files contain: "Dog Cat and Chair Table", the program should display: "Cat Chair Dog Table".
Example Code
package Text;
import java.util.*;
public class Main
{
public static void main(String[] args)
{
System.out.print("Enter name of file1: ");
String nameFile1 = new Scanner(System.in).nextLine();
System.out.print("Enter name of file2: ");
String nameFile2 = new Scanner(System.in).nextLine();
if ((!(new java.io.File(nameFile1)).isFile()) || (!(new java.io.File(nameFile2)).isFile()))
{
System.out.print("File 1 or File 2 not exists");
return;
}
try
{
java.io.FileReader myfile = new java.io.FileReader(nameFile1);
java.io.BufferedReader myfileBufferedReader = new java.io.BufferedReader(myfile);
ArrayList list = new ArrayList();
String line;
do
{
line = myfileBufferedReader.readLine();
if (line != null)
{
list.add(line);
}
} while (line != null);
myfile.close();
myfile = new java.io.FileReader(nameFile2);
line = "";
do
{
line = myfileBufferedReader.readLine();
if (line != null)
{
list.add(line);
}
} while (line != null);
myfile.close();
Collections.sort(list);
for (int i = 0; i < list.size(); i++)
{
System.out.println(list.get(i));
}
}
catch (RuntimeException e)
{
System.out.println("Error al intentar abir el fichero.");
}
}
}