Question

I am trying to read a file that changes dynamically and display its contents in jTextArea. I am using buffered reader for reading.

I have tried to display the contents on console and it works fine, but doesn't work with jTextArea.

I am doing something like

while(true)
{
  line = br.readLine();
  if(line == null)
    Thread.sleep();
  else
    System.out.println(line);
}

Any help would be appreciated. Thanks

Was it helpful?

Solution

Don't use Thread.sleep(), you will block the EDT. Instead use a javax.swing.Timer if you want to "animate" the results. Just read each line each iteration of the timer, until it reaches the end of the file, then stop the timer

timer = new Timer(100, new ActionListener() {
     public void actionPerformed(ActionEvent e) {
          String line;
           try {
                if ((line = reader.readLine()) != null) {
                    textArea.append(line + "\n");
                } else {
                   ((Timer) e.getSource()).stop();
                }
           } catch (IOException ex) {
                Logger.getLogger(ReadFile.class.getName()).log(Level.SEVERE, null, ex);
           }
     }
});

Test this program out. I think it works the way you want it to.

import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
import javax.swing.Timer;

public class ReadFile {

    File file = null;
    BufferedReader reader = null;

    private Timer timer = null;
    private JTextArea textArea;
    private JTextField jtfFile;
    private String fileName;
    private JButton browse;
    private JFrame frame;

    public ReadFile() {
        textArea = new JTextArea(25, 60);
        frame = new JFrame("Show Log");

        browse = new JButton("Browse");
        browse.addActionListener(new ShowLogListener());

        jtfFile = new JTextField(25);
        jtfFile.addActionListener(new ShowLogListener());

        timer = new Timer(100, new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                String line;
                try {
                    if ((line = reader.readLine()) != null) {
                        textArea.append(line + "\n");
                    } else {
                        ((Timer) e.getSource()).stop();
                    }
                } catch (IOException ex) {
                    Logger.getLogger(ReadFile.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        });

        JPanel panel = new JPanel();
        panel.add(new JLabel("File: "));
        panel.add(jtfFile);
        panel.add(browse);

        frame.add(panel, BorderLayout.NORTH);
        frame.add(new JScrollPane(textArea), BorderLayout.CENTER);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.pack();
        frame.setLocationByPlatform(true);
        frame.setVisible(true);
    }

    private class ShowLogListener implements ActionListener {

        @Override
        public void actionPerformed(ActionEvent e) {
            JFileChooser chooser = new JFileChooser();
            int result = chooser.showOpenDialog(frame);
            if (result == JFileChooser.APPROVE_OPTION) {
                file = chooser.getSelectedFile();
                fileName = file.getName();
                jtfFile.setText(fileName);
                try {
                    reader = new BufferedReader(new FileReader(file));
                } catch (FileNotFoundException ex) {
                    Logger.getLogger(ReadFile.class.getName()).log(Level.SEVERE, null, ex);
                }
                timer.start();
            }
        }
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable(){
            public void run() {
                new ReadFile();
            }
        });
    }
}

enter image description here

OTHER TIPS

2 points:

  • Don't call Thread.sleep() in the EDT. This blocks the UI and prevents UI updates
  • JTextArea has a read method that allows files to be loaded

Example:

JTextArea textArea = new JTextArea();
textArea.read(new FileReader("input.txt"), "blah");
String line;    
String textToDisplay = "";
while((line = br.readLine()) != null)
    textToDisplay+=line;
textArea.setText(textToDisplay);

I used setText(String) instead of append(String) because it'll replace what is already is in the JTextArea... From your question I felt that's what you wanted to do.

You have to set the text of the text area..try doing so:

{
 line = br.readLine();
 if(line == null)
     Thread.sleep();
 else
     textArea.append(line + "\n");
}

this will append (put text at end) of the file, meaning that you will not have to worry about text being deleted each time it runs

that should work, hope it helps

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top