I want to read lines from a file and it does not work for me JAVA

0

Very good guys! I'm trying to read lines of a type ".txt" even though I have it in .test, it's the same. What I have to do is read the first 6 lines, and then read the lines one by one (every time I enter ENTER I go to the next line) until there are no more.

This is my main code, I cut it because you only need to see where I execute it:

public class Main {

private void printMenu(String p) { //String per imprimir els menus dels tests
    System.out.println("Has triat " + p);
    System.out.println("Selecciona el test que vols fer");
    System.out.println("");
    System.out.println(" 1 - Dificultat baixa");
    System.out.println(" 2 - Dificultat normal");
    System.out.println(" 3 - Dificultat alta");
}


private void run() {
    LT lt = new LT();
    char lletra = ' ';
    int real = ' ';
    String Nom; //String on es guarda el nom
    System.out.println("Benvingut a la pràctica de tests");
    System.out.println("");
    System.out.println("Quin és el teu nom?");
    Nom = lt.llegirLinia(); //Lletgeix l'escrit per teclat i ho guarda al string
    System.out.println("");
    System.out.println("Benvingut " + Nom); //PROVA

    while (lletra != 'd' && lletra != 'D') { //Feim un while per triar opció

        System.out.println("");
        System.out.println("Selecciona una de les opcions següents:");
        System.out.println("");
        System.out.println("'A' ---> Tests disponibles");
        System.out.println("'B' ---> Tutorial");
        System.out.println("'C' ---> Historial de partides");
        System.out.println("'D' ---> Sortir del programa");
        System.out.println("");

        lletra = lt.llegirCaracter();
        switch (lletra) { //El switch el cream per poder fer diferentes opcions                

            case 'A': //Opció per jugar
            case 'a':
                System.out.println("Tests disponibles");
                System.out.println("");
                System.out.println("Selecciona el tema del text: ");
                System.out.println("'N' - Naturalesa ");
                System.out.println("'A' - Animals ");
                System.out.println("'V' - Videojocs ");
                System.out.println("'C' - Cotxes ");
                System.out.println("");
                System.out.println("Per tornar al menú prinicpal tecletja T");

                while (lletra != 't' && lletra != 'D') { //Triam el temari dels tests
                    lletra = lt.llegirCaracter();

                    switch (lletra) {

                        case 'N':
                        case 'n':
                            printMenu("Naturalesa");
                            real = lt.llegirSencer();
                            switch (real) {
                                case 1: {
                                    try {
                                        Lectura lr = new Lectura("Naturalesa/4.test");

                                    } catch (IOException ex) {
                                        Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
                                    }
                                }
                                break;
                                case 2:
                                    System.out.println("Naturalesa/5.test");
                                    break;
                                case 3:
                                    System.out.println("Naturalesa/6.test");
                                    break;
                            }
                            break;

                        case 'A':
                        case 'a':
                            printMenu("Animals");
                            break;

                        case 'V':
                        case 'v':
                            printMenu("Videojocs");
                            break;

                        case 'C':
                        case 'c':
                            printMenu("Cotxes");
                            break;

                        default: //Error que surt si l'usuari introdueix una lletra incorrecte
                            System.out.println("Opción no váilda");
                            break;
                    }
                }
                break;

            case 'B': //Opció per sebrer com es juga 'Tutorial'
            case 'b':
                System.out.println("Tutorial");
                Tutorial.alTutorial();
                break;

            case 'C': //Opció per vorer l'historial de les darreres partides
            case 'c':
                System.out.println("Historial de partides");
                break;

            case 'D': //Opció per sortir del programa
            case 'd':
                System.out.println("Sortir del programa");
                break;

            default: //Error que surt si l'usuari introdueix una lletra incorrecte
                System.out.println("Opción no váilda");
                break;

        }
    }
}

And here is the class I use to read:

public class Reading {

FileReader fr;
BufferedReader bf;

public Lectura (String FitxerLletgit) throws IOException {
    try {
        fr = new FileReader(FitxerLletgit); //Agafam el FitxerLletgit amb el FileReader
        bf = new BufferedReader(fr); //Agafam el "fr" que té el fitxer i el guardam al "bf"
       //System.out.println(bf.readLine());
        while ((bf.readLine()) != null) {
            for (int i = 0; i < 3; i++) {
               String st;
               st = bf.readLine();
               System.out.println(st); 
            }   
        }
    } catch (FileNotFoundException ex) {
        System.out.println(ex);
    }       
}

}

Here I am putting a for length three, I have tried with the .lenght of the string that I use to put the file but neither. I do not know where the problem lies, I guess in the class I read, but I do not know, I've tried watching YouTube videos but none of them help me or I do not understand it.

PS: It's in Catalan, if you have difficulty reading it I can change the language

    
asked by Pedro 27.12.2018 в 01:07
source

1 answer

1

The problem occurs when calling the function readLine() , this function returns the current line, and increases the current line position for the next iteration. By calling it so many times, the reader moves more than you expect.
That is, you do not need the for cycle, but if you need to save the line of text in a variable when you call readLine() .
Here is an example that only reads and writes the number of lines specified, for a file given by a path.

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;

public class Main {

    public static void main(String[] args) throws IOException {
        writeFileLines("archivo.test", 6);
    }

    /**
     * Escribe las primeras N líneas de texto de un archivo.
     *
     * @param path  Ruta de acceso al archivo.
     * @param count Cantidad de líneas a obtener.
     * @throws IOException
     */
    public static void writeFileLines(String path, int count) throws IOException {
        FileInputStream fis = new FileInputStream(path);                        // almacena en memoria el archivo a leer.
        BufferedReader br = new BufferedReader(new InputStreamReader(fis));     // buffer de lectura.

        String tmpLine;     // almacenará temporalmente las líneas de texto.

        // ciclo de lectura: leerá solo si existen líneas para leer y la cantidad de líneas pendientes es mayor a cero.
        while ((tmpLine = br.readLine()) != null && 0 < count) {
            System.out.println(tmpLine);    // escribe la línea de texto actual.
            count--;                        // reduce el contador de líneas de texto pendientes.
        }

        br.close();     // cierra para liberar recursos.
    }
}
    
answered by 27.12.2018 в 02:22