Read java txt file data and perform Java operations

Asked

Viewed 2,097 times

0

I am making a vehicle rental company in java need to read from a txt the type of client(char) a date range(string) and the amount of passengers(int).

I need to bring this data to be analyzed , for example according to the passenger Qtd I do calculations of which car is most suitable and according to the type of customer I do the calculation of fees, according to the day of the week has different values.

But I don’t know and I didn’t find any plausible explanation of how I do this linkage of the file variables to the correct variables in the code anyone can help me?

I’ll have you read the file:

private static void ler() {
            File dir = new File("C:\\Arquivos");
            File arq = new File(dir, "LocadoraCarro.txt");

            try {
                FileReader fileReader = new FileReader(arq);
                BufferedReader bufferedReader = new BufferedReader(fileReader);
                String linha = "";
                while ( ( linha = bufferedReader.readLine() ) != null) {
                System.out.println(linha);
            }

                fileReader.close();
                bufferedReader.close();
            } catch (IOException e) {
                e.printStackTrace();
            }

        }               

File Format : TIPO_DO_CLIENTE: QUANTIDADE_PASSAGEIROS: DATA1, DATA2, DATA3

Example: Normal: 2: 12Abr2018 (mon), 13Abr2018(Tue)

  • There are two different doubts there, I suggest you separate and leave only one, which is the txt reading.

  • And you speak of a txt file but it does not show any lines demonstrative of this file. Edit the question and add a few lines of this file to facilitate understanding.

  • @Article made the requested changes.

2 answers

0


That’s pretty quiet to do, what should be getting in the way is the way you’re looking at the problem.

First I used a class to represent the die, called Data. This class has nothing else. Just some attributes, setters, getters and an implementation of the method toString().

And the methods getClientType(String[] split), getNPassengers(String[] split) and parseDates(String[] split) retrieve each attribute of the class Data given a file line.

In the method readFile(String filePath), Each line read from the file a new instance of the Data class is created and added to a list. Each element of this list represents a row of the input file.

Full class:

public class Main {

    private static class Data{
        private String clientType;
        private int nPassagers;
        private String[] dates;

        public Data(String clientType, int nPassagers, String[] dates) {
            this.clientType = clientType;
            this.nPassagers = nPassagers;
            this.dates = dates;
        }

        public String getClientType() {
            return clientType;
        }

        public void setClientType(String clientType) {
            this.clientType = clientType;
        }

        public int getnPassagers() {
            return nPassagers;
        }

        public void setnPassagers(int nPassagers) {
            this.nPassagers = nPassagers;
        }

        public String[] getDates() {
            return dates;
        }

        public void setDates(String[] dates) {
            this.dates = dates;
        }

        @Override
        public String toString() {
            return "Data{" +
                    "clientType='" + clientType + '\'' +
                    ", nPassagers=" + nPassagers +
                    ", dates=" + Arrays.toString(dates) +
                    '}';
        }
    }

    private static List<Data> readFile(String filePath){
        File arq = new File(filePath);

        List<Data> dataList = new ArrayList<>();

        try {
            FileReader fileReader = new FileReader(arq);
            BufferedReader bufferedReader = new BufferedReader(fileReader);
            String linha = "";
            while ((linha = bufferedReader.readLine()) != null) {
                String[] split = linha.split(":");
                dataList.add(new Data(getClientType(split), getNPassengers(split), parseDates(split)));
            }

            fileReader.close();
            bufferedReader.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return dataList;
    }

    private static String getClientType(String[] split){
        if (split == null || split.length == 0){
            return null;
        }

        return split[0];
    }

    private static int getNPassengers(String[] split){
        if (split == null || split.length < 2 || split[1] == null){
            return -1;
        }

        return Integer.valueOf(split[1].trim());
    }

    private static String[] parseDates(String[] split){
        if (split == null || split.length < 3 || split[2] == null){
            return null;
        }

        return split[2].trim().split(",");
    }

    public static void main(String[] args){
        List<Data> result = readFile("LocadoraCarro.txt");

        for (Data data : result){
            System.out.println(data.toString());
        }
    }
}

0

First, I’m not sure what your goal is when using a TXT file, but the ideal in this situation is to use a database, which already has the whole mechanism to process the data.

But since your case is a TXT, no problem! As in an application that uses a database, we will use object orientation to represent the data in our program.

For this, I suggest that you do a little research on object orientation, for now I will explain the basics so that you can continue after...

To represent your txt data, we will create a class containing the respective attributes that you want to recover from txt

package br.com.cogerh.template.model;

import java.util.List;

public class File {

//ESSE ATRIBUTO IRÁ REPRESENTAR UM CLIENTE
private String cliente;

//LISTA COM TODAS AS DATAS
private List<String> data;

//QUANTIDADE DE PASSAGEIROS
private Integer qtdPassageiros;

public Arquivo(){

}


public Arquivo(String cliente, List<String> data, Integer qtdPassageiros) {
    super();
    this.cliente = cliente;
    this.data = data;
    this.qtdPassageiros = qtdPassageiros;
}

public void implementacaoMetodo1(){
    System.out.println("EXEMPLO DE IMPLEMENTACAO DO METODO 1");
}

public void implementacaoMetodo2(){
    System.out.println("EXEMPLO DE IMPLEMENTACAO DO METODO 2");

}


public String getCliente() {
    return cliente;
}

public void setCliente(String cliente) {
    this.cliente = cliente;
}

public List<String> getData() {
    return data;
}

public void setData(List<String> data) {
    this.data = data;
}

public Integer getQtdPassageiros() {
    return qtdPassageiros;
}

public void setQtdPassageiros(Integer qtdPassageiros) {
    this.qtdPassageiros = qtdPassageiros;
}

}

Done this, we have our class represents customers! In this class we also have examples of methods that will serve for you to implement your fee calculation rules and etc...

The next step is to call the txt class the Client class we just created and pass the values through the class constructor or the set methods of the attributes.

Browser other questions tagged

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