Java Swing How to - Read file content inside SwingWorker








Question

We would like to know how to read file content inside SwingWorker.

Answer

//from  w ww. jav a  2  s  .  co m
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import javax.swing.JFrame;
import javax.swing.JProgressBar;
import javax.swing.SwingWorker;

public class Main {
  public static void main(String[] args) {
    JProgressBar pb = new JProgressBar(0, 100);
    ReadFileWorker worker = new ReadFileWorker();
    worker.addPropertyChangeListener(new PropertyChangeListener() {
      @Override
      public void propertyChange(PropertyChangeEvent evt) {
        if ("progress".equalsIgnoreCase(evt.getPropertyName())) {
          pb.setValue(worker.getProgress());
        }
      }
    });
    JFrame f = new JFrame();
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    f.add(pb);
    f.pack();
    f.setVisible(true);
    worker.execute();
  }
}
class ReadFileWorker extends SwingWorker<List<String>, String> {
  @Override
  protected List<String> doInBackground() throws Exception {
    List<String> lines = new ArrayList<>(25);
    File textFile = new File("c:/Java_Dev/run.bat");
    long byteLength = textFile.length();

    System.out.println("Reading " + byteLength + " bytes...");

    try (InputStream is = new FileInputStream(textFile)) {
      byte[] content = new byte[1024];
      int bytesRead = -1;
      long totalBytes = 0;
      while ((bytesRead = is.read(content)) != -1) {
        totalBytes += bytesRead;
        setProgress(Math.round(((float) totalBytes / (float) byteLength) * 100f));
        String text = new String(content);
        lines.add(text);
        publish(text);
        Thread.sleep(1000);
      }
      System.out.println("Read " + totalBytes + " bytes...");
      System.out.println("Read " + lines.size() + " lines...");
    }
    return lines;
  }
  @Override
  protected void done() {
    try {
      List<String> lines = get();
      System.out.println(lines);
    } catch (Exception ex) {
      ex.printStackTrace();
    }
  }
}