archivos...para definir un archivo de salida, creamos un objeto de tipo printwriter. printwriter...

12
Ing. Roberto Martínez Román - [email protected] 1 Archivos GUARDANDO Y RECUPERANDO INFORMACIÓN EN JAVA ING. ROBERTO MARTÍNEZ ROMÁN - [email protected] Flujos de datos ING. ROBERTO MARTÍNEZ ROMÁN - [email protected] Los programas pueden leer/escribir datos desde distintos dispositivos del sistema Flujo de entrada Flujo de Salida

Upload: others

Post on 24-Jan-2021

2 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Archivos...Para definir un archivo de salida, creamos un objeto de tipo PrintWriter. PrintWriter salida = new PrintWriter(new FileWriter("datos.txt")); El objeto salidase procesa como

Ing. Roberto Martínez Román [email protected] 1

ArchivosGUARDANDO Y RECUPERANDO INFORMACIÓN EN JAVA

ING. ROBERTO MARTÍNEZ ROMÁN [email protected]

Flujos de datos

ING. ROBERTO MARTÍNEZ ROMÁN [email protected]

Los programas pueden leer/escribir datos desde distintos dispositivos del sistema

Flujo de entrada

Flujo de Salida

Page 2: Archivos...Para definir un archivo de salida, creamos un objeto de tipo PrintWriter. PrintWriter salida = new PrintWriter(new FileWriter("datos.txt")); El objeto salidase procesa como

Ing. Roberto Martínez Román [email protected] 2

Entrada/Salida en consola

ING. ROBERTO MARTÍNEZ ROMÁN [email protected]

Existen 3 flujos predefinidos para leer/escribir en consola.

System.in. Flujo de entrada estándar

System.out. Flujo de salida estándar

System.err. Flujo de errores estándar

La clase ScannerSe utiliza para leer datos desde la consola de entrada (teclado, System.in).

Scanner teclado = new Scanner(System.in);

nombre = teclado.nextLine(); // lee una cadena

edad = teclado.nextLine(); // lee un entero

estatura = teclado.nextDouble(); // lee un número real

casado = teclado.nextBoolean(); // lee un valor lógico

ING. ROBERTO MARTÍNEZ ROMÁN - [email protected]

Page 3: Archivos...Para definir un archivo de salida, creamos un objeto de tipo PrintWriter. PrintWriter salida = new PrintWriter(new FileWriter("datos.txt")); El objeto salidase procesa como

Ing. Roberto Martínez Román [email protected] 3

EjercicioEscribe un programa que lea los datos de una persona: nombre, edad, estatura y si está casado o no.

ING. ROBERTO MARTÍNEZ ROMÁN - [email protected]

Archivos de entrada

ING. ROBERTO MARTÍNEZ ROMÁN [email protected]

FileReader ent = new FileReader("nombre.txt");

La clase FileReader define métodos básicos de lectura de caracteres.

BufferedReader entrada = new BufferedReader( ent );

La clase BufferedReader define métodos para leer caracteres, arreglos de caracteres o líneas de texto.

Page 4: Archivos...Para definir un archivo de salida, creamos un objeto de tipo PrintWriter. PrintWriter salida = new PrintWriter(new FileWriter("datos.txt")); El objeto salidase procesa como

Ing. Roberto Martínez Román [email protected] 4

Leyendo datos del archivo

ING. ROBERTO MARTÍNEZ ROMÁN [email protected]

BufferedReader entrada = new BufferedReader(new FileReader("datos.txt"));

String linea = entrada.readLine();

El método readLine lee caracteres del flujo de entrada hasta encontrar una nueva línea '\n'. Si no hay datos para leer, regresa null.

entrada.close();

El método close cierra el flujo, libera el recurso asignado por el sistema operativo.

Leyendo datos del archivo

ING. ROBERTO MARTÍNEZ ROMÁN [email protected]

BufferedReader entrada = new BufferedReader(new FileReader("datos.txt"));

while ( entrada.ready() ) {

String linea = entrada.readLine();

// Procesa línea

}

entrada.close();

Page 5: Archivos...Para definir un archivo de salida, creamos un objeto de tipo PrintWriter. PrintWriter salida = new PrintWriter(new FileWriter("datos.txt")); El objeto salidase procesa como

Ing. Roberto Martínez Román [email protected] 5

Excepciones usando archivos

ING. ROBERTO MARTÍNEZ ROMÁN [email protected]

Los métodos utilizados para crear y usar archivos lanzan excepciones de tipo IOException, las cuales son verificadas.

Los métodos que usan estas operaciones, deben tener una instrucción try-catch o indicar que la excepción es ignorada. (throws)

Consulta el API para conocer los diferentes tipos de excepciones que generan las operaciones con archivos.

Ejemplo

ING. ROBERTO MARTÍNEZ ROMÁN [email protected]

Escribe código para abrir un archivo de entrada (texto) e imprimir su contenido en un componente gráfico.

Agregue a su ejercicio, código para numerar cada línea.

Page 6: Archivos...Para definir un archivo de salida, creamos un objeto de tipo PrintWriter. PrintWriter salida = new PrintWriter(new FileWriter("datos.txt")); El objeto salidase procesa como

Ing. Roberto Martínez Román [email protected] 6

1: import java.io.BufferedReader;2: import java.io.IOException;3: import java.io.FileReader;4: 5: public class PruebaArchivos 6: {7: public static void main(String[] args) throws IOException {8: 9: BufferedReader entrada = new BufferedReader(new FileReader("PruebaArchivos.java"));10: int numLinea=0;11: while ( entrada.ready() ) {12: 13: String linea = entrada.readLine();14: numLinea++;15: System.out.println(numLinea + ": " + linea);16: }17: 18: entrada.close();19: }20: }

Solución (para consola)BufferedReader entrada =

new BufferedReader(new FileReader("PruebaArchivos.java"));

int numLinea=0;while ( entrada.ready() ) {

String linea = entrada.readLine();numLinea++;

System.out.println(numLinea + ": " + linea);}

entrada.close();

ING. ROBERTO MARTÍNEZ ROMÁN [email protected]

Procesando palabras de un archivo de texto

ING. ROBERTO MARTÍNEZ ROMÁN [email protected]

La clase StringTokenizer proporciona la funcionalidad de descomponer un String en componentes llamados tokens.

StringTokenizer st = new StringTokenizer(línea); // Separador " ", por default

StringTokenizer st = new StringTokenizer(línea,separador); // Podemos indicar el separador con un String

while ( st.hasMoreTokens() ) {

String palabra = st.nextToken();

// Procesa la palabra

}

Page 7: Archivos...Para definir un archivo de salida, creamos un objeto de tipo PrintWriter. PrintWriter salida = new PrintWriter(new FileWriter("datos.txt")); El objeto salidase procesa como

Ing. Roberto Martínez Román [email protected] 7

Procesando palabras de un archivo de texto

ING. ROBERTO MARTÍNEZ ROMÁN [email protected]

La clase String proporciona el método split que ayuda a descomponer un String en componentes llamados tokens.

String a = "Hola mundo adios x335!-sf";String b[] = a.split(" ");System.out.println(Arrays.toString(b));

[Hola, mundo, adios, x335!-sf]

Ejemplo

Clave Existencia100-A253-C290-A315-D

35722948

ING. ROBERTO MARTÍNEZ ROMÁN [email protected]

Dado un archivo de texto con datos de clave de producto y existencia, escriba código para calcular el total de productos en existencia. Los datos en cada línea están separados por un tabulador. (No sabemos el número de líneas que hay en el archivo)

Page 8: Archivos...Para definir un archivo de salida, creamos un objeto de tipo PrintWriter. PrintWriter salida = new PrintWriter(new FileWriter("datos.txt")); El objeto salidase procesa como

Ing. Roberto Martínez Román [email protected] 8

Archivos de salida

ING. ROBERTO MARTÍNEZ ROMÁN [email protected]

Para definir un archivo de salida, creamos un objeto de tipo PrintWriter.

PrintWriter salida = new PrintWriter(new FileWriter("datos.txt"));

El objeto salida se procesa como si usáramos System.out (print y println)

Archivos de salida

ING. ROBERTO MARTÍNEZ ROMÁN [email protected]

Si el archivo ya existe, normalmente se destruye y se crea uno nuevo. Para evitar que se borren los datos existentes, se usa el siguiente formato:

PrintWriter salida = new PrintWriter(new FileWriter("datos.txt", true));

Page 9: Archivos...Para definir un archivo de salida, creamos un objeto de tipo PrintWriter. PrintWriter salida = new PrintWriter(new FileWriter("datos.txt")); El objeto salidase procesa como

Ing. Roberto Martínez Román [email protected] 9

Escribiendo datos al archivo

ING. ROBERTO MARTÍNEZ ROMÁN [email protected]

PrintWriter salida = new PrintWriter(new FileWriter("datos.txt"));

salida.println("Datos al archivo");

salida.println("Otros\nDatos");

salida.println("Edad: " + edad);

salida.printf("Estatura: %.2f", est);

salida.close();

Ejemplo

ING. ROBERTO MARTÍNEZ ROMÁN [email protected]

Escriba código para generar un archivo de salida de texto que contenga 20 números aleatorios entre 10 y 100.

Agrega 20 números más al archivo generado.

Page 10: Archivos...Para definir un archivo de salida, creamos un objeto de tipo PrintWriter. PrintWriter salida = new PrintWriter(new FileWriter("datos.txt")); El objeto salidase procesa como

Ing. Roberto Martínez Román [email protected] 10

SoluciónPrintWriter salida = new PrintWriter(new FileWriter("datos.txt"));

for(int i=1; i<=20; i++) {

salida.println( (int)(Math.random()*100)+1 );

}

salida.close();

ING. ROBERTO MARTÍNEZ ROMÁN [email protected]

201235689033828846655449056983479888688

SoluciónPrintWriter salida = new PrintWriter(new FileWriter("datos.txt",true));

for(int i=1; i<=20; i++) {

salida.println( (int)(Math.random()*100)+1 );

}

salida.close();

ING. ROBERTO MARTÍNEZ ROMÁN [email protected]

20123568903382884665544905698347988868870546471979056811636147159265208982659

Page 11: Archivos...Para definir un archivo de salida, creamos un objeto de tipo PrintWriter. PrintWriter salida = new PrintWriter(new FileWriter("datos.txt")); El objeto salidase procesa como

Ing. Roberto Martínez Román [email protected] 11

Leyendo archivos, con la clase Scanner

ING. ROBERTO MARTÍNEZ ROMÁN [email protected]

Scanner sc = new Scanner(new FileReader("hola.txt"));

while ( sc.hasNextLine() ) {

System.out.println("Línea: " + sc.nextLine());

}

Para leer datos individuales

ING. ROBERTO MARTÍNEZ ROMÁN [email protected]

Scanner sc = new Scanner(new FileReader("hola.txt"));

while ( sc.hasNext() ) {

String nombre = sc.next();

int c1 = sc.nextInt();

int c2 = sc.nextInt();

}

Roberto 100 90Margarito 80 75

Page 12: Archivos...Para definir un archivo de salida, creamos un objeto de tipo PrintWriter. PrintWriter salida = new PrintWriter(new FileWriter("datos.txt")); El objeto salidase procesa como

Ing. Roberto Martínez Román [email protected] 12

Ejemplo usando Scanner

Clave Existencia100-A253-C290-A315-D

35722948

ING. ROBERTO MARTÍNEZ ROMÁN [email protected]

Dado un archivo de texto con datos de clave de producto y existencia, escriba código para calcular el total de productos en existencia. Los datos en cada línea están separados por un tabulador. (No sabemos el número de líneas que hay en el archivo)