How to display the contents of a .txt file on the screen?

3

I am using JFrame to try to display the contents of txt files in a window and then delete the whole file. However, when I put it to display, it deletes the file but does not display on the screen that I created with JFrame . What could be happening?

Follow the code:

/*
 * 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 Sistema;

import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import javax.swing.JOptionPane;

/**
 *
 * @author marqu
 */
public class NewJFrame extends javax.swing.JFrame {

    /**
     * Creates new form NewJFrame
     */
    public NewJFrame() {
        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() {

        lab = new javax.swing.JLabel();
        jButton1 = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        lab.setBackground(new java.awt.Color(204, 204, 255));
        lab.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        lab.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        lab.setText("Controle da Catraca");

        jButton1.setText("Exibir historico");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(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()
                        .addContainerGap()
                        .addComponent(lab, javax.swing.GroupLayout.PREFERRED_SIZE, 372, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(142, 142, 142)
                        .addComponent(jButton1)))
                .addContainerGap(18, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(38, 38, 38)
                .addComponent(jButton1)
                .addGap(18, 18, 18)
                .addComponent(lab, javax.swing.GroupLayout.DEFAULT_SIZE, 210, Short.MAX_VALUE)
                .addContainerGap())
        );

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

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

        String dir = "C:/Users/marqu/OneDrive/Documentos/marco.txt"; //String com o diretorio do arquivo txt
        Path caminho = Paths.get(dir); //Informa o caminho do arquivo txt
        byte[] txt = null;

        try {
            while (true) {

                do {
                    txt = Files.readAllBytes(caminho);// Ler o arquivo txt
                } while (txt.length <= 0); //Enquanto o arquivo txt estiver vazio, fique preso nesse WHILE

                //System.out.println(); // METODO TEMPORARIO SO PARA VISUALIZAR
                lab.setText(new String(txt));
                Files.write(caminho, "".getBytes()); // Apaga tudo do arquivo txt
            }
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }



    }                                        

    /**
     * @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(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new NewJFrame().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify                     
    private javax.swing.JButton jButton1;
    private javax.swing.JLabel lab;
    // End of variables declaration                   
}
    
asked by anonymous 10.11.2017 / 20:50

1 answer

1

This infinite loop is the cause of application crash, alias, you do not need these two loops to do what you intended. Swing applications run on a single thread called , and any longer activity should be done on another thread, called . Making an infinite loop in the button action will keep the application locked.

Change the button method as below:

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

    // diretorio do arquivo txt
    String dir = "C:/Users/marqu/OneDrive/Documentos/marco.txt";
    Path caminho = Paths.get(dir);
    List<String> txt;

    try {
        txt = Files.readAllLines(caminho);
        StringBuilder builder = new StringBuilder();

        for (String s : txt)
            builder.append(s);

        lab.setText(builder.toString());

        Files.write(caminho, "".getBytes());

    } catch (Exception e) {
        System.out.println(e.getMessage());

    }
}                                     

What I've changed is to change the type from%% variable to a string list, which is the return of the txt method. With this array loaded, I created a Files.readAllLines() to be able to load the lines of the file into a string and finally add it to its component. This last step would not be necessary, but if the file has multiple lines, it is interesting to do so if you need to manipulate the lines separately.

However, StringBuilder was not meant to display multi-line text. Unless the content of your file is a single line, that's fine, but if it's multiple lines, I suggest you use a JLabel . If you'd like to learn more about this component, see this official tutorial teaching you how to use it.

If the goal is to update the component automatically with a defined interval after the click event of the button, see a solution in this response .

    
10.11.2017 / 23:21