package iesthiar; import java.io.File; import java.io.FileNotFoundException; import java.io.FileWriter; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.ArrayList; import java.util.List; import java.util.Scanner; public class Ejercicio_B4 { public static void main(String[] args) { int numPersonas; String ruta; try (Scanner teclado = new Scanner(System.in)){ System.out.print("NĂºmero de nombres de personas a generar: "); numPersonas = teclado.nextInt(); teclado.nextLine(); System.out.print("Ruta donde quiere guardar el archivo generado: "); ruta = teclado.nextLine(); // Ficheros para lectura File fileNombres = new File("target/classes/iesthiar/Documentos/usa_nombres.txt"); File fileApellidos = new File("target/classes/iesthiar/Documentos/usa_apellidos.txt"); // ArrayList con los datos de los ficheros de lectura //ArrayList listaNombres = leerDatosFichero(fileNombres); ArrayList listaApellidos = leerDatosFichero(fileApellidos); List listaNombres=Files.readAllLines(Paths.get("target/classes/iesthiar/Documentos/usa_nombres.txt")); // Generamos el nombre y apellido aleatoriamente y lo escribimos en el fichero try ( // FileWriter para escritura FileWriter writer = new FileWriter(new File(ruta))) { // Generamos el nombre y apellido aleatoriamente y lo escribimos en el fichero for (int i = 0; i < numPersonas; i++) { int indexNom = (int) (Math.random() * listaNombres.size()); int indexApe = (int) (Math.random() * listaApellidos.size()); writer.write(listaNombres.get(indexNom) + " " + listaApellidos.get(indexApe) + "\n"); } // Cerramos FileWriter y mensaje final } System.out.println("Fichero generado correctamente: " + ruta); } catch (FileNotFoundException e) { System.out.println("Error: El fichero no existe"); } catch (IOException e) { System.out.println("Error: " + e); } catch (Exception e) { System.out.println("Error: " + e); } } // Devuelve un ArrayList con los datos leidos del fichero public static ArrayList leerDatosFichero(File f) throws FileNotFoundException { try ( Scanner lector = new Scanner(f);){ ArrayList lista = new ArrayList<>(); while (lector.hasNext()) { lista.add(lector.nextLine()); } return lista; } catch (Exception e){ throw new FileNotFoundException(e.getMessage()); } } }