generated from programacionThiar/plantilla_iesthiar-maven-21
70 lines
2.7 KiB
Java
70 lines
2.7 KiB
Java
|
|
package iesthiar;
|
||
|
|
|
||
|
|
import java.io.File;
|
||
|
|
import java.io.FileNotFoundException;
|
||
|
|
import java.io.FileWriter;
|
||
|
|
import java.io.IOException;
|
||
|
|
import java.util.ArrayList;
|
||
|
|
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<String> listaNombres = leerDatosFichero(fileNombres);
|
||
|
|
ArrayList<String> listaApellidos = leerDatosFichero(fileApellidos);
|
||
|
|
|
||
|
|
// 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<String> leerDatosFichero(File f) throws FileNotFoundException {
|
||
|
|
try ( Scanner lector = new Scanner(f);){
|
||
|
|
ArrayList<String> lista = new ArrayList<>();
|
||
|
|
while (lector.hasNext()) {
|
||
|
|
lista.add(lector.nextLine());
|
||
|
|
}
|
||
|
|
return lista;
|
||
|
|
} catch (Exception e){
|
||
|
|
throw new FileNotFoundException(e.getMessage());
|
||
|
|
}
|
||
|
|
}
|
||
|
|
}
|