Lendo arquivos e colocando em uma TextField

Bom dia!

Estou com um problema!

Tenho um programa onde posso cadastrar Verbetes

Este é o código da parte gráfica

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package tela;

import java.io.FileWriter;
import javax.swing.JOptionPane;
import negocio.Palavra;

/**
 *
 * @author André
 */
public class CadastroVerbete extends javax.swing.JDialog {

    /**
     * Creates new form CadastroVerbete
     */
    public CadastroVerbete(java.awt.Frame parent, boolean modal) {
        super(parent, modal);
        initComponents();
    }

    CadastroVerbete() {
        initComponents();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
    private void initComponents() {

        jTextFieldId = new javax.swing.JTextField();
        jTextFieldPalavra = new javax.swing.JTextField();
        jLabelCadastroVerbete = new javax.swing.JLabel();
        jLabelId = new javax.swing.JLabel();
        jLabelPalavra = new javax.swing.JLabel();
        jLabelSignificado = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTextAreaSignificado = new javax.swing.JTextArea();
        jLabelFonte = new javax.swing.JLabel();
        jTextFieldFonte = new javax.swing.JTextField();
        jButtonSalvarVerbete = new javax.swing.JButton();
        jButtonSair = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);

        jTextFieldId.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jTextFieldIdActionPerformed(evt);
            }
        });

        jTextFieldPalavra.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jTextFieldPalavraActionPerformed(evt);
            }
        });

        jLabelCadastroVerbete.setFont(new java.awt.Font("Dialog", 1, 18)); // NOI18N
        jLabelCadastroVerbete.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        jLabelCadastroVerbete.setText("Cadastro de Verbete");

        jLabelId.setFont(new java.awt.Font("Dialog", 1, 14)); // NOI18N
        jLabelId.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
        jLabelId.setText("ID");
        jLabelId.setToolTipText("");

        jLabelPalavra.setFont(new java.awt.Font("Dialog", 1, 14)); // NOI18N
        jLabelPalavra.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        jLabelPalavra.setText("Palavra");
        jLabelPalavra.setToolTipText("");

        jLabelSignificado.setFont(new java.awt.Font("Dialog", 1, 14)); // NOI18N
        jLabelSignificado.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        jLabelSignificado.setText("Significado");
        jLabelSignificado.setToolTipText("");

        jTextAreaSignificado.setColumns(20);
        jTextAreaSignificado.setRows(5);
        jScrollPane1.setViewportView(jTextAreaSignificado);

        jLabelFonte.setFont(new java.awt.Font("Dialog", 1, 14)); // NOI18N
        jLabelFonte.setText("Fonte");

        jButtonSalvarVerbete.setText("Salvar Verbete");
        jButtonSalvarVerbete.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonSalvarVerbeteActionPerformed(evt);
            }
        });

        jButtonSair.setText("Sair");
        jButtonSair.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonSairActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(199, 199, 199)
                        .addComponent(jLabelCadastroVerbete, javax.swing.GroupLayout.PREFERRED_SIZE, 202, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(44, 44, 44)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addGap(23, 23, 23)
                                .addComponent(jLabelId, javax.swing.GroupLayout.PREFERRED_SIZE, 63, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addGap(18, 18, 18))
                            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                                    .addComponent(jLabelPalavra, javax.swing.GroupLayout.PREFERRED_SIZE, 63, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addComponent(jLabelSignificado)
                                    .addComponent(jLabelFonte))
                                .addGap(26, 26, 26)))
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(jButtonSalvarVerbete)
                                .addGap(41, 41, 41)
                                .addComponent(jButtonSair, javax.swing.GroupLayout.PREFERRED_SIZE, 89, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                                .addComponent(jTextFieldFonte, javax.swing.GroupLayout.Alignment.LEADING)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(jTextFieldId, javax.swing.GroupLayout.PREFERRED_SIZE, 55, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                                        .addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 325, Short.MAX_VALUE)
                                        .addComponent(jTextFieldPalavra, javax.swing.GroupLayout.Alignment.LEADING)))))))
                .addContainerGap(129, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(26, 26, 26)
                .addComponent(jLabelCadastroVerbete, javax.swing.GroupLayout.DEFAULT_SIZE, 39, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabelId)
                    .addComponent(jTextFieldId, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(20, 20, 20)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabelPalavra)
                    .addComponent(jTextFieldPalavra, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabelSignificado)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabelFonte)
                    .addComponent(jTextFieldFonte, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jButtonSalvarVerbete)
                    .addComponent(jButtonSair))
                .addGap(13, 13, 13))
        );

        pack();
        setLocationRelativeTo(null);
    }// </editor-fold>                        

    private void jTextFieldIdActionPerformed(java.awt.event.ActionEvent evt) {                                             


    }                                            

    private void jTextFieldPalavraActionPerformed(java.awt.event.ActionEvent evt) {                                                  
        // TODO add your handling code here:
    }                                                 

    private void jButtonSalvarVerbeteActionPerformed(java.awt.event.ActionEvent evt) {                                                     
        Palavra palavras = new Palavra();

        palavras.setId(jTextFieldId.getText());
        palavras.setPalavra(jTextFieldPalavra.getText());
        palavras.setSignificado(jTextAreaSignificado.getText());
        palavras.setFonte(jTextFieldFonte.getText());
        JOptionPane.showMessageDialog(null, palavras.salvar());

        jTextFieldId.setText("");
        jTextFieldPalavra.setText("");
        jTextFieldFonte.setText("");
        jTextAreaSignificado.setText("");
    }                                                    
                
    private void jButtonSairActionPerformed(java.awt.event.ActionEvent evt) {                                            
        dispose();
    }                                           

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(CadastroVerbete.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(CadastroVerbete.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(CadastroVerbete.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(CadastroVerbete.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the dialog */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                CadastroVerbete dialog = new CadastroVerbete(new javax.swing.JFrame(), true);
                dialog.addWindowListener(new java.awt.event.WindowAdapter() {
                    @Override
                    public void windowClosing(java.awt.event.WindowEvent e) {
                        System.exit(0);
                    }
                });
                dialog.setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify                     
    private javax.swing.JButton jButtonSair;
    private javax.swing.JButton jButtonSalvarVerbete;
    private javax.swing.JLabel jLabelCadastroVerbete;
    private javax.swing.JLabel jLabelFonte;
    private javax.swing.JLabel jLabelId;
    private javax.swing.JLabel jLabelPalavra;
    private javax.swing.JLabel jLabelSignificado;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTextArea jTextAreaSignificado;
    private javax.swing.JTextField jTextFieldFonte;
    private javax.swing.JTextField jTextFieldId;
    private javax.swing.JTextField jTextFieldPalavra;
    // End of variables declaration                   
}

E aqui uma imagem de como ela é
image

Ao criar um verbete um arquivo com nome verbetes.txt é criado automaticamente, conforme anexo abaixo!

image

O arquivo txt fica assim com o separador “;”.

Aqui esta o código que usei para salvar o arquivo

public Object salvar() {

        try {
            FileWriter fw = new FileWriter("verbetes.txt", true);
            PrintWriter pw = new PrintWriter(fw);
            pw.println(this.id + ";" + this.palavra + ";" + this.significado + ";" + this.fonte + "\n");
            pw.flush();
            pw.close();
            fw.close();

        } catch (IOException ex) {
            Logger.getLogger(Palavra.class.getName()).log(Level.SEVERE, null, ex);
        }

        return "Verbete Cadastrado";
    }

Porém, eu preciso agora ler esse TxT e demonstrar as palavras em uma lista, eu não sei como fazer isto e nem qual a melhor forma de demonstrar isso graficamente. Pensei em um JTable ou TextField mesmo
A Interface que deve demonstrar a lista é essa

Não sei como faria parar o ler o arquivo e listar as palavras, e nem um método de como realizar a pesquisa nessa lista que seria criada.

Alguém poderia me ajudar?

Muito Obrigado!

1 curtida

Por quê vc não usa a lib commons-io para ler o Arquivo?
Exemplo:

List<String> lines = FileUtils.readLines(new File("path_to"), Charsets.UTF_8)
1 curtida

Do mesmo modo da CommonsIO você pode usar a API NIO que é do própio java.

List<String> lines = Files.readAllLines(Path.of("verbetes.txt"));

E também usar o método replaceAll da classe List para remover os pontos e vírgulas.

lines.replaceAll(line -> line.replace(";", " "));
2 curtidas