generated from programacionThiar/plantilla_iesthiar-maven-21
Ejercicio B Completos
This commit is contained in:
77
src/main/java/iesthiar/Ejercicio_B1v2.java
Normal file
77
src/main/java/iesthiar/Ejercicio_B1v2.java
Normal file
@@ -0,0 +1,77 @@
|
||||
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);
|
||||
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user