Files
t12ficheros-ejerciciosB/src/main/java/iesthiar/Ejercicio_B1v2.java
2024-05-26 18:43:25 +02:00

78 lines
2.2 KiB
Java
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

package iesthiar;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import java.util.Scanner;
/**
* Implementa un programa que muestre por pantalla los valores máximos y mínimos del archivo numeros.txt.
*
*/
public class Ejercicio_B1v2 {
public static void main(String[] args) {
int minimo=Integer.MAX_VALUE;
int maximo=Integer.MIN_VALUE;
// Leer de un fichero. Ruta relativa
File fichero=new File("Documentos/numeros.txt");
// Usamos try-for-resources. No hace falta cerrar, se cierra solo
try (Scanner entrada=new Scanner(fichero)){
// Leemos mientras tengamos datos
while (entrada.hasNext()) {
int numero=entrada.nextInt();
if (numero<minimo)
minimo=numero;
if (numero>maximo)
maximo=numero;
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.printf("Con Scanner: El mínimo es %d y el máximo es %d%n",minimo,maximo);
// Usando FileReader/BufferedReader
minimo=Integer.MAX_VALUE;
maximo=Integer.MIN_VALUE;
try (BufferedReader br = new BufferedReader(new FileReader("Documentos/numeros.txt"))) {
String linea;
while ((linea = br.readLine()) != null) {
int numero=Integer.parseInt(linea);
if (numero<minimo)
minimo=numero;
if (numero>maximo)
maximo=numero;
}
} catch (IOException e) {
System.err.println("Error al leer el archivo: " + e.getMessage());
}
System.out.printf("Con FileReader/BufferedReader: El mínimo es %d y el máximo es %d%n",minimo,maximo);
//Usando nio
minimo=Integer.MAX_VALUE;
maximo=Integer.MIN_VALUE;
Path path = Paths.get("Documentos/numeros.txt");
try {
List<String> lines = Files.readAllLines(path);
for (String line : lines) {
int numero=Integer.parseInt(line);
if (numero<minimo)
minimo=numero;
if (numero>maximo)
maximo=numero;
}
} catch (IOException ex) {
System.err.println("Error al leer el archivo: " + ex.getMessage());
}
System.out.printf("Con nio: El mínimo es %d y el máximo es %d%n",minimo,maximo);
}
}