Java shortcut files

6

What I need to know is why when I enter a record to read, I skip the exception EOF that says there are no more records in the file. I have created in the code that each record that has a length of 44 bytes to go directly to a record. Then I wanted to know what my fault is .. I tell him that I want to go to register 1 and I skip the exception. Can you make me an example file, or tell me where the fault is?

import java.io.*;
import java.util.Scanner;
class Principal{
    public static void main(String [] args) {
        int longRegistro, n, id;
        double salario;
        String apellido;
        Scanner lectura = new Scanner (System.in);
        RandomAccessFile entrada = null;
        String nombreFichero;
        try {
            System.out.println("Introduzca el nombre del fichero");
            nombreFichero = lectura.next();
            entrada = new RandomAccessFile(nombreFichero, "r");
            System.out.println("Introduzca el numero de registro a leer");
            n = lectura.nextInt();
            longRegistro = 44; //4 bytes (int), 30(String)+2 UTF, 8(double)
            entrada.seek((n - 1) * longRegistro);
            id = entrada.readInt();
            apellido = entrada.readUTF();
            salario = entrada.readDouble();
            System.out.printf("%d %s %.2f\n", id, apellido, salario);
        }
        catch (EOFException e) {
            System.out.println("\nHa llegado al final del fichero. "    +   "El numero de registro no existe.");
        }
        catch (FileNotFoundException e) {
            System.out.println("El fichero especificado no existe");
        }
        catch(IOException e) {
            System.out.println("Excepcion de entrada/salida:" +
            e.toString());
            System.out.println(e.getMessage());
        }
        finally {
        try {
            entrada.close();
        }
        catch (IOException io) {
            System.out.println("No se ha podido cerrar el fichero" +io.toString());
            System.out.println(io.getMessage());
        }
       } // Fin finally
    } // Fin método main
}  
    
asked by gabriel gomez 18.05.2016 в 21:38
source

1 answer

1

Seeing that you still have no answer and based on the conversation of the comments, I'm going to propose a much simpler and shorter way to read and pause the data of a model file like the one you propose :

FILE: ( datos.txt )

1 Gabriel 10.5
2 Jordi 340.23
3 Javi 432

Principal.java (I've put the option to read the whole file to show you another way to read)

private static final String FOLDER  = "D:\Users\VEMIJCS\_1\";

public static void main(String[] args) throws Exception {
    Scanner in = new Scanner(System.in);
    System.out.print("nombre fichero ");
    String file = in.nextLine();
    System.out.print("fila a leer (0 todas) ");
    int row = in.nextInt(); 
    in.close();

    BufferedReader reader = new BufferedReader(new FileReader(FOLDER + file)); 
    String line = "";

    // mostramos todo el fichero
    if (row == 0) {
        while ((line = reader.readLine()) != null) {
            print(line);
        }
    } else {
        // leemos hasta la linea que nos han pedido
        for (int i = 0; i < row; i++) { 
            line = reader.readLine();
            if (line == null) { 
                System.out.println("no existe la linea numero " + row);
                System.exit(0);
            }
        }

        // e imprimimos
        print(line);
    }
    reader.close();
}

private static void print(String line) {
    int numero      = Integer.parseInt(line.trim().split(" ")[0]);
    String nombre   = line.trim().split(" ")[1];
    double valor    = Double.parseDouble(line.trim().split(" ")[2]);

    System.out.println(nombre.toUpperCase() + " ocupa la linea numero: " + numero + " y tiene un valor de " + valor);

}

OUTPUT FOR VALID LINE NUMBER

nombre fichero datos.txt
fila a leer (0 todas) 2
JORDI ocupa la linea numero: 2 y tiene un valor de 340.23

DEPARTURE FOR LINE NUMBER == 0

nombre fichero datos.txt
fila a leer (0 todas) 0
GABRIEL ocupa la linea numero: 1 y tiene un valor de 10.5
JORDI ocupa la linea numero: 2 y tiene un valor de 340.23
JAVI ocupa la linea numero: 3 y tiene un valor de 432.0

DEPARTURE FOR NON-VALID LINE NUMBER

nombre fichero datos.txt
fila a leer (0 todas) 9
no existe la linea numero 9

NOTES

  • Imports needed:

    import java.io.BufferedReader;
    import java.io.FileReader;
    import java.util.Scanner;
    
  • I have not performed exception control to parsed the data but do not forget to implement it in case the data in the file is not correct.

  • The file must be located in the corresponding FOLDER directory.
  • If you have any questions, contact me :) .
answered by 07.07.2016 в 13:42