1 / 24

Archivos y Búsqueda Secuencial

Archivos y Búsqueda Secuencial. Profesora Lillian Bras. Archivos de Entrada y Salida. En muchas ocasiones es necesario mantener los datos en memoria secundaria para uso futuro y para esto existen los archivos.

helene
Télécharger la présentation

Archivos y Búsqueda Secuencial

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Archivos y Búsqueda Secuencial Profesora Lillian Bras

  2. Archivos de Entrada y Salida • En muchas ocasiones es necesario mantener los datos en memoria secundaria para uso futuro y para esto existen los archivos. • Un archivo puede ser creado para escribir en él o para leer de él y decimos que son archivos de entrada o de salida según sea el caso(input /output files). • En general existen dos tipos de archivos: archivos binarios y archivos de texto (Por el momento estaremos usando los de texto.) • En terminos generales para utilizar archivos debemos: • Abrir el archivo • Crear una variable(nombre lógico) que represente el archivo físico y establecer una asociación entre ambos • Cerrar el archivo al terminar de usarlo

  3. Archivo de Salida(Output File): • Para abrir el archivo para output(escribir en él), se tiene que crear una instancia de la clase PrintWriter;en otras palabras, crear un objeto tipo PrintWriter. PrintWriter outputFile = new PrintWriter("StudentData.txt"); Aquí se coloca el nombre físico con su extensión entre comillas. Cuidado: si el archivo ya existe, lo borra y se reemplaza con lo que se escriba.

  4. La clase PrintWriter • Para usar la clase PrintWriter es necesario incluir la siguiente instrucción al comienzo del código fuente:import java.io.*; • La clase PrintWriter permite que se escriba a un archivo usando los métodos print y println, que usted ya conoce. • Los métodos println y print funcionan con los archivos igual que para la pantalla. • println: coloca un caracter correspondiente a un cambio de línea después de los datos escritos • print: escribe los datos sin ningún cambio de línea.

  5. Pasos importantes al usar archivo de salida Abrir archivo PrintWriter outputFile = new PrintWriter("Names.txt"); outputFile.println("Chris"); outputFile.println("Kathryn"); outputFile.println("Jean"); outputFile.close(); Cerrar archivo Escribir al archivo Nota:No olvide que necesita la instrucción import java.io.* para poder usar la clase PrintWriter

  6. Ejemplo con clase PrintWriter import java.util.Scanner; // Needed for Scanner class import java.io.*; // Needed for File I/O classes /** This program writes data to a file */ public class FileWriteDemo { public static void main(String[] args) throws IOException { String friendName; // Friend's name int numFriends; // Number of friends // Create a Scanner object for keyboard input. Scanner keyboard = new Scanner(System.in); // Get the number of friends. System.out.print("How many friends do you have? "); numFriends = keyboard.nextInt(); // Consume the remaining newline character. keyboard.nextLine(); Continúa

  7. Continuación del ejemplo con la clase PrintWriter… // Open the file. PrintWriter outputFile = new PrintWriter(“myData.txt”); // Get data and write it to the file. for (int i = 1; i <= numFriends; i++) { // Get the name of a friend. System.out.print("Enter the name of friend " + "number " + i + ": "); friendName = keyboard.nextLine(); // Write data to the file. outputFile.println(friendName); } // Close the file. outputFile.close(); System.out.println("Data written to the file."); } }

  8. Para entrar el nombre del Archivo por el teclado… public static void main(String[] args) throws IOException { String filename; // File name String friendName; // Friend's name int numFriends; // Number of friends // Create a Scanner object for keyboard input. Scanner keyboard = new Scanner(System.in); // Get the filename. System.out.print("Enter the filename: "); filename = keyboard.nextLine(); // Get the number of friends. System.out.print("How many friends do you have? "); numFriends = keyboard.nextInt(); // Consume the remaining newline character. keyboard.nextLine(); // Open the file. PrintWriter outputFile = new PrintWriter(filename); // Rest of theprogram is the same…

  9. Pseudocódigo para el ejercicio del registro de notas Abrir archivo For( sec=1 To cantSecciones) Obtener sección Escribir seccion en el archivo de salida Obtener cantidad de estudiantes en esa seccion For( est = 1 To cantEstudiantes) Obtener datos del estudiante: nombre y tres notas Calcular el promedio Mostrar nombre y promedio Escribir nombre y promedio al archivo de salida EndFor Escribir línea en blanco al archivo EndFor Cerrar Archivo

  10. Archivos de entrada(Input File) • Para leer de un archivo que ya fue creado se utiliza la clase File y la clase Scanner. Aquí se coloca el nombre del archivo físico Nombre lógico del archivo File myFile = new File("Customers.txt"); Scanner inputFile = new Scanner(myFile); Aqui se escribe el nombre lógico declarado en la instrucción anterior

  11. Flujograma del ciclo para leer de un archivo Abrir archivo Hay algún dato por leer? True Leer dato/s Y Procesar dato/s False

  12. Para leer de un archivo • Para leer de un archivo podemos usar un for (si sabemos la cantidad de líneas y que datos por línea) o utilizamos el caracter que marca el final del archivo (eof) con un ciclo while • En Java, para detectar el final del archivo, se usa el método hasNext() de la clase Scanner. Este método devuelve true si existe algo mas por leerse que no sea el “eof”. • El siguiente segmento en Java, demuestra como usar hasNext(), en un ciclo while, para leer de un archivo: // Open the file. Scanner keyboard = new Scanner(System.in); System.out.print("Enter the filename: "); String filename = keyboard.nextLine(); File file = new File(filename); Scanner inputFile = new Scanner(file); // Read until the end of the file. while (inputFile.hasNext()) { String friendName = inputFile.nextLine(); System.out.println(friendName); } inputFile.close();// close the file when done.

  13. Instrucciones antes del ciclo del código anterior… Scanner keyboard = new Scanner(System.in); System.out.print("Enter the filename: "); String filename = keyboard.nextLine(); File myFile = new File(filename); Scanner inputFile = new Scanner(myFile); • En las líneas anteriores: • Se crea un objeto (keyboard) de la clase Scanner para leer del teclado • Se le solicita al usuario que entre el nombre del archivo • Se declara una variable tipo String para recoger el nombre del archivo del teclado • Se crea un objeto tipo File para representar el archivo (myFile) • Se crea un objeto tipo Scanner para leer del archivo(inputFile)

  14. Ciclo de lectura en código anterior… // Read until the end of the file. while (inputFile.hasNext()){ String firiendName= inputFile.nextLine(); System.out.println(friendName); } inputFile.close();// close the file when done. • inputFile.hasNext() verifica si lo próximo a leerse es el marcador eof. Si lo es devuelve falso y si no, es porque hay un dato para leer, y devuelve cierto, en cuyo caso entra al ciclo. • Esta instrucción lee una línea del archivo y la guarda en str. (Note que se usa el nombre de la variable (inputFile), que se declaró tipo Scanner, en vez del acostunmbrado nombre keyboard) • Se muestra lo que se leyó del archivo • Se cierra el archivo al salir del ciclo

  15. Ejemplo para leer nombres… import java.util.Scanner; // Needed for the Scanner class import java.io.*; // Needed for the File class // este archivo se creo con elcon el primer ejemplo visto en esta presentación public class FileReadDemo { public static void main(String[] args) throws IOException { // Create a Scanner object for keyboard input. Scanner keyboard = new Scanner(System.in); // Get the filename. System.out.print("Enter the filename: "); String filename = keyboard.nextLine(); // Open the file. File file = new File(filename); Scanner inputFile = new Scanner(file); // Read lines from the file until no more are left. while (inputFile.hasNext()) { // Read the next name. String friendName = inputFile.nextLine(); // Display the last name read. System.out.println(friendName); } // Close the file. inputFile.close(); } }

  16. Verificacando si el archivo de entrada existe… • Si tratamos de abrir y leer de un archivo que no existe tendremos un error en etapa de ejecución muy poco deseable. • Para evitar que el programa interrumpa abruptamente la ejecución porque el archivo no existe o no lo encuentre, debemos incluir un if que verifique dicha situación. • La siguiente instrucción se usa para verificar la no-existencia del archivo: if( ! inputFile.exists() ) { System.out.println(“Error! File not found.”); System.exit(0); } • El método .exixts() devuelve falso si el archivo no existe, por eso la necesidad del operador de negación(!). (De esta forma podemos usar un if sin else.) • Note la instrucción de System.exit(0) que se incluye dentro del bloque para que, de no existir el archivo, termine el programa después del mensaje.

  17. Ejemplo que verifica existencia de archivo de entrada(Autor:Profesor Antonio Huertas) import java.io.*; import java.text.DecimalFormat; import java.util.Scanner; /*This program reads the data of a list of employees from a file and computes the salary for each one. */ public class EmployeeFileReadApp3 { public static void main(String[] args) throws IOException { // Define symbolic constants final int STD_WORKING_WEEK = 40; final double OVERTIME_RATE = 1.5; // Declare variables for employee data and number of employees String id, firstName, lastName; double payRate, salary; int hoursWorked, overtime; int numEmployees = 0; // Create a reference to a decimal format DecimalFormat formatter = new DecimalFormat("$#,##0.00"); // Create a reference to the employee file and check whether it exists File employeeFile = new File("employees.txt"); if (! employeeFile.exists()) { System.out.println("File does not exist!"); System.exit(0); }

  18. // Open employee file for reading (input) Scanner inputFile = new Scanner(employeeFile); // While there is data in input file... while (inputFile.hasNext()) { // Read employee data from input file id = inputFile.next(); firstName = inputFile.next(); lastName = inputFile.next(); payRate = inputFile.nextDouble(); hoursWorked = inputFile.nextInt(); System.out.println("Data has been read from employee file."); // Increment number of employees read numEmployees++; // Compute salary if (hoursWorked <= STD_WORKING_WEEK) salary = payRate * hoursWorked; else { overtime = hoursWorked - STD_WORKING_WEEK; salary = (payRate * STD_WORKING_WEEK) +(payRate * overtime * OVERTIME_RATE); } // Display employee data and salary System.out.println("Employee #" + numEmployees + ":"); System.out.println("\tId: " + id); System.out.println("\tName: " + firstName + " " + lastName); System.out.println("\tPay Rate: " + formatter.format(payRate)); System.out.println("\tHours Worked: " + hoursWorked); System.out.println("\tSalary: " + formatter.format(salary)); System.out.println(); } System.out.println("There are " + numEmployees + " employees."); // Close input file inputFile.close(); }}

  19. Búsqueda Secuencial o Lineal • La búsqueda de un dato en una lista es una tarea que necesitamos llevar a cabo en muchas ocasiones. • Si necesitamos buscar un dato en una lista donde los datos no están ordenados, es necesario revisar un dato tras otro en secuencia hasta tanto lo encontremos o se terminen los datos. • No importa si los datos están almacenados en un archivo de memoria secundaria, son entrados por algún equipo de entrada, o están en un arreglo de memoria primaria, el algoritmo que se utiliza para hacer la búsqueda secuencial es basicamente el mismo.

  20. Algoritmo general de Búsqueda Secuencial 1.Obtener dato ha ser buscado : searchItem 2. Inicializar variable lógica en falso: found = falso 3. While ( there is more data and search item has not been found) get item from list If( item = searchItem) then display item found = true End If End While 4. If Not found then display(“Item not found”) End if

  21. Pseudocódigo Búsqueda Secuencial en archivo 1. Open file 2. found = false 3. Get searchItem 4. While (more data in file and not found) read data from file If (data = searchItem ) then found = true display info End If End While 5. If ( not found) then display (“That item is not in the file”) End If 6. Close file

  22. Ejemplo Búsqueda Secuencial en Java … import java.io.*; import java.util.Scanner; /*This program reads the data of a list of students from a file to perform a linear search. Prof. Lillian Bras */ public class SequentialSearchApp{ public static void main(String[] args) throws IOException { // Declare variables String id,; double average; char grade; // Create a reference to the student file and check whether it exists File studentFile = new File(“studentData.txt"); if (! studentFile.exists()) { System.out.println("File does not exist!"); System.exit(0); } // Open student file for reading (input) Scanner inputFile = new Scanner(studentFile);

  23. Ejemplo en Java… // Create a Scanner object for keyboard input. Scanner keyboard = new Scanner(System.in); // Get SearchId from user System.out.print("Enter the Student’s Id you are looking for "); String searchId= keyboard.nextLine(); // Initialize logic variable found boolean found = false; // While there is data in input file item has not been found... while (inputFile.hasNext() && !found) { // Read student data from input file id = inputFile.next(); average = inputFile.nextDouble(); grade = inputFile.next(). charAt(0); // compare id’s if (id.equals(searchId){ found = true; System.out.println(“Average: ” + average); System.out.println(“Grade: ” + grade); } } If(!found) System.out.println(“Student not in file.”); // Close input file inputFile.close(); } }

  24. Recuerde: • Si lo que tenemos es un grupo de datos relacionados entre sí como: id de estudiante, nombre de estudiante, promedio de estudiante y nota de estudiante la búsqueda se hace por uno de ellos siempre y cuando este no se repita (sea único en la lista). • Casi siempre la búsqueda se hace por seguro social o algún número de identificación que sea único. • En un archivo de texto para llegar a un dato es necesario leer todo lo que está antes aunque no se vaya a utilizar. • Necesitamos conocer que tipos de datos y en que orden están en el archivo para poder leer adecuadamente cada uno de ellos. Recuerde que su programa dirige la computadora en el proceso de lectura.

More Related