Reading of files in Java

Asked

Viewed 72 times

0

public static void loadfile(stock []a) throws IOException{

        String fich;
        File fichDad;
        int i=countDatas(a);

        while(sc.nextLine().length()!=0);
        do{
            System.out.print("\nQual é o nome do ficheiro que deseja ler?\n");
            fich=sc.nextLine();
            fichDad = new File(fich);
        }while(!fichDad.canRead()||!fichDad.exists()||!fichDad.isFile());

        Scanner lerFil = new Scanner (fichDad);

        while (lerFil.hasNextLine()){
            if(i==100) break;
            if(!lerFil.hasNext()) break;; 

            a[i]=new stock();
            a[i].nome=lerFil.next();
            a[i].quant=lerFil.nextInt();
            i++;
        }

        System.out.print("\n\n\nValores inseridos com sucesso!\n\n\n\n");

        lerFil.close();

}

I am doing an exercise that consists of a program (in Java) for stock maintenance in a store. The program is working, but there’s a "problem" I can’t solve. The program does all operations correctly and then the progress made can be saved in a file, which can then be read and loaded into the program to resume progress. However, if you read the files twice in a row, instead of deleting what you have in your memory and writing over it, the function displays twice the contents of the file. Someone has a solution?

  • 1

    can share your reading code?

  • I’m sorry I forgot to add. I already added

  • What is countDatas(a)?

  • Where does the variable come from sc? 'Cause you clean her entire entrance?

  • countDatas(a) is a function that counts the number of elements in the array. sc is the scanner

1 answer

0


You can rewrite your class Stock thus:

import java.io.File;
import java.io.Scanner;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class Stock {
    private final String nome;
    private final int quantidade;

    public Stock(String nome, int quantidade) {
        this.nome = nome;
        this.quantidade = quantidade;
    }

    public String getNome() {
        return nome;
    }

    public int getQuantidade() {
        return quantidade;
    }

    public static List<Stock> loadFile(Scanner sc) throws IOException {
        // Limpa o sc.
        while (!sc.nextLine().isEmpty());

        File ficheiro;
        do {
            System.out.print("\nQual é o nome do ficheiro que deseja ler?\n");
            String nomeFicheiro = sc.nextLine();
            ficheiro = new File(nomeFicheiro);
        } while (!ficheiro.exists() || !ficheiro.isFile() || !ficheiro.canRead());

        List<Stock> lista = new ArrayList<>();
        try (Scanner leitor = new Scanner(ficheiro)) {
            for (int i = 0; i < 100 && leitor.hasNext(); i++) {
                String nome = leitor.next();
                int quantidade = leitor.nextInt();
                Stock s = new Stock(nome, quantidade);
                lista.add(s);
            }
        }

        System.out.println("Valores inseridos com sucesso!");

        return lista;
    }
}

Note that it will always return a new list of Stock containing the contents of the file. Use the Try-with-Resources and follow code conventions.

To replace then the list, just do this:

Scanner sc = new Scanner(System.in);

// Primeira vez.
List<Stock> lista = Stock.loadFile(sc);

// ...Um monte de código aqui...

// Segunda vez.
lista = Stock.loadFile(sc);
  • thank you very much!

  • but there is no way to do without using builders and lists?

  • @Martimneves certainly does exist. You can use arrays instead of lists (including you used them) or design your own equivalent data structure to store the data sequence and you can build objects by calling the setters later or directly in the attributes (as you did). However, I do not recommend any of these approaches, which is why I did the answer in exactly this way. Working with arrays is somewhat difficult and lists are much more flexible and easy to handle. As for using the constructors, this is due to: https://answall.com/a/252986/132

  • thank you very much!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.