Tracking the progress of reading from an InputStream

You can use the class ProgressMonitorInputStream as described
on Sun’s page How to Monitor Progress.

Main.java:

import java.awt.event.*;
import javax.swing.*;
import java.awt.*;
import java.io.*; 
 
public class Main extends JFrame implements ActionListener {
   JTextField fileTextField;
 
   public Main() {
      addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent we) {
            System.exit(1);
         }
      }); 
       
      JPanel panel = new JPanel();
      panel.setLayout(new FlowLayout(FlowLayout.LEFT));
      panel.add(new JLabel("File:"));
      fileTextField = new JTextField(20);
      panel.add(fileTextField);
      JButton loadButton = new JButton("Load!");
      panel.add(loadButton);
      loadButton.addActionListener(this);
 
      fileTextField.setText("c:\jdk1.2.2\lib\tools.jar");
 
      getContentPane().setLayout(new BorderLayout());
      getContentPane().add(BorderLayout.NORTH, panel);
      pack();
   } 
 
   public void actionPerformed(ActionEvent ae) {
      FileLoader worker = new FileLoader(this, fileTextField.getText());
      worker.start();
   }
 
   class FileLoader extends Thread {
      Component parentComponent;
      String fileName; 
      ProgressMonitor progressMonitor;
 
      public FileLoader(Component parentComponent, String fileName) {
         this.parentComponent = parentComponent;
         this.fileName = fileName;
      }
 
      public void run() {
         try {
            ProgressMonitorInputStream pmis = new ProgressMonitorInputStream(
                                                parentComponent,
                                                "Reading " + fileName,
                                                new FileInputStream(fileName));
            progressMonitor = pmis.getProgressMonitor();
            BufferedInputStream bis = new BufferedInputStream(pmis);
            
            byte b[] = new byte[1024];
            int bytes = bis.read(b, 0, b.length);
            while (bytes > 0) {
               try {
                  Thread.sleep(10);
               }
               catch(InterruptedException e) { } 
               bytes = bis.read(b, 0, b.length);
            }
 
            System.out.println("Loaded!");
         }
         catch(InterruptedIOException e) {
            if (progressMonitor.isCanceled()) {
               System.out.println("Loading of " + fileName + " has been cancelled!");
            }
            else {
               System.out.println(e);
            }
         }
         catch(IOException e) {
            System.out.println(e);
         }
      }
   }
 
   public static void main(String []args) {
      Main main = new Main();
      main.setVisible(true);
      main.setSize(350, 150);
   }
}