how to join lines in a text file and create a folder automatically on disk

Asked

Viewed 144 times

0

Given a text file as described below:

MARIA;5;MPOO
MARIA;3;AED
MARIA;5;MPOO
JOHN;1;IP

How to create a logic to obtain a result (which groups by equal names and discipline and adds the interactions), such as:
MARIA;10;MPOO
MARIA;3;AED
JOHN;1;IP

I managed to create, as in the code below, just to show everything in separate lines, but I’m not able to put it together. This code takes the student’s name, the number of times he interacted with a subject and what the subject.

public class ArquivoInteracao {

//ESSA PASTA NO C: SÓ É CRIADA SE EU FOR LÁ MANUALMENTE E CRIÁ-LA, EXISTE ALGUMA FORMA DELA 
//SER CRIADA AUTOMATICAMENTE?
static java.io.File diretorio = new java.io.File("C:\\Venera");
boolean statusDir = diretorio.mkdir();
public static File arquivo = new File(diretorio, "exibirInteracao.txt");


public ArquivoInteracao() {
    try {
        boolean statusArq = arquivo.createNewFile();

    } catch (IOException e) {
        e.printStackTrace(); 
    } 
}
private static StringBuilder mensagem;

public static List<String> Read(String Caminho) {
    List<String> conteudo = new ArrayList<>();

    try {
        // Files.readAllLines existe a partir do Java 1.7 em diante
        List<String> linhas = Files.readAllLines(arquivo.toPath());

        for (String linha : linhas) {
            conteudo.add(linha);
        }
    } catch (IOException ex) {
        System.out.println("Erro: Não foi possível ler o arquivo!");
    } catch (Exception ex) {
        System.out.println("Erro: Arquivo não encontrado!");
    }

    return conteudo;
}

public static boolean Write(String Texto) {
    try {
        if (!arquivoExiste()) {
            arquivo.createNewFile();
            System.out.println("not");
        }

        System.out.println("Yes");
        FileWriter arq = new FileWriter(arquivo, true);
        PrintWriter gravarArq = new PrintWriter(arq);
        gravarArq.println(Texto);
        gravarArq.close();

        return true;
    } catch (IOException e) {
        System.out.println(e.getMessage());
        return false;
    }
}

public static void salvar(AlunoCliente ac) {
    String print = ControleTelaInicial.nomeAlunoParaInteracao + ";" + ControllerPainel.contInteração + ";" +
            ControleTelaInicial.comboAlunoParaInteracao;
    
     if (ArquivoInteracao.Write(print)) {
            System.out.println("Arquivo salvo com sucesso!");
        } else {
            System.out.println("Erro ao salvar o arquivo!");
        }
}

public static void mostrar(){
    try {
        List<String> linhas = ArquivoInteracao.Read("exibirInteracao.txt");
        mensagem = new StringBuilder();
        
        if (linhas != null && !linhas.isEmpty()) {
            for (int i = 0; i < linhas.size(); i++) {
                //JÁ TENTEI JUNTAR, MAS NÃO CONSEGUI
                String nome = (linhas.get(i).split(";")[0]);
                int qtdeInteracao = Integer.parseInt(linhas.get(i).split(";")[1]);
                String disciplina = (linhas.get(i).split(";")[2]);
                mensagem.append(nome+ "você interagiu"+ qtdeInteracao +"vezes na disciplina de"+ disciplina+"\n");
            }
        }

    } catch (IndexOutOfBoundsException e3) {
        System.out.println("Nada a exibir: " + e3.getMessage());
    }
}

public static boolean arquivoExiste() {
    return arquivo.exists();
}
public static StringBuilder getMensagem() {
    return mensagem;
}
}
  • 1
    1. Do not try to do procedural programming in Java. The result is very bad. Understand the OO paradigm and what the objects represent. 2) Know the data structures you are using. A ArrayList is just a list. It does not miracle. Do not do split() 3x to pick up an item in each. Make a split() only and store in an array. Then refer to the index. Tip: create a class Interacao with the single key Nome;Disciplina and delegate to it the sum of interactions. The class ArquivoInteracao just need to know how to manipulate the files.
  • I have to do so because it is for a college project. But you can explain me better, because I could not understand!?

  • I can’t get into the logic of how to put these lines together and add up results, it’s very complex

  • You don’t have to do it that way unless the problem statement is "Make a Pascal program using the Java language." The algorithm is + or - like this: Open the file; Read the lines; Add the values where the name and discipline are equal; Save the consolidated result in another file. There you have several options to add up. I suggested that you make an Interaction object to make the sum. But if you want to do everything procedural, you can sort the list and then scroll through it by adding each new line to an accumulated value. More than that, only if I do your job for you.

  • This is a very simple question, which uses 3 fundamental concepts for any programmer: 1) Algorithms 2) Data Structures and 3) Object Orientation. If you UNDERSTAND these 3 concepts, will never complain that lack programmer jobs or earn little. Good studies and success!

  • But how is the logic to know if they are equal? the equals of not right

  • But you could answer me if there is how to create the folder automatically and not manually?

Show 2 more comments

1 answer

0

I answered with SQL.

public void mostrarInteracao() {
    String disciplina = "";
    String aluno = "";
    int qtd = 0;
    System.out.println("1");
    
    String sql = "SELECT nomeAluno , disciplina , SUM(qtdInteracao) FROM tabelaInteracao GROUP BY disciplina";

    try {
        pst = conexaoBD.prepareStatement(sql);
        rs = pst.executeQuery();
        // int numero = 0;

        while (rs.next()) {
            // numero = 1;
            aluno = (rs.getString("nomeAluno"));
            disciplina = (rs.getString("disciplina"));
            qtd = (rs.getInt("SUM(qtdInteracao)"));

            textArea.append("Aluno(a): " +aluno +"\n"+"Disciplina: "+ disciplina +"\n"+ "N° de participação: " + qtd +"\n"+ "\n");

        }

    } catch (Exception ed) {
    }
}

Browser other questions tagged

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