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

Asked

Viewed 885 times

3

I’m using JFrame to try to display the contents of txt files in a window and then delete the entire file. However, when I put it to display, it erases the file no longer displays on the screen I created with JFrame. What may be happening?

Follows 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                   
}
  • This code is not executable. Adds the full code of your jframe so we can test the problem.

  • already added brother

1 answer

1

This infinite loop is the cause of the application lock, alias, it doesn’t need these two loops to do what you want. Swing applications run in a single thread, called , and any longer activity should be done on another thread, called . Make infinite loop in 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 changing the type of the variable txt for a string list, which is the return of the method Files.readAllLines(). With this array loaded, I created a StringBuilder to be able to load the file lines into a string and finally add them to its component. This last step would not be necessary, but if the file has multiple lines, it is interesting to do it if you need to manipulate the lines separately.

However, JLabel was not made to display multi-line texts. Unless the contents of your file are a single line, it won’t be a problem, but if it’s multiple lines, I suggest you use a JTextArea. If you want to learn more about this component, see this official tutorial teaching how to use it.

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

  • the loop and the following, has a program that will always be adding lines of text in a file . txt, and this program will take these lines of text display in a window and delete the file. txt, ai will always be checking the file picking up what has in this file displaying and erasing

  • @Marcoantonio See the update in the answer suggesting reading a solution psosivel other problem.

Browser other questions tagged

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