如何在读取文本文件时使用Java进度条?

时间:2014-04-19 07:33:07

标签: java multithreading swing io jprogressbar

我是java swing的新手,我想读取文本文件。在读取该文件时,我想在java进度条中显示已读取行的百分比。欢迎任何示例代码。我试过,但我不知道我的逻辑是否正确。我怎么能实现这个目标。

import java.io.*;
import javax.swing.*;
import javax.swing.UIManager.*;
import javax.swing.border.EtchedBorder;
public class UploadFile 
{  
JFrame frame;
JProgressBar progressBar_1;
public static void main(String args[])throws IOException
{  
    UploadFile obj=new UploadFile();
    obj.redfile();
}  
public UploadFile()
{
    frame = new JFrame();
    frame.setBounds(100, 100, 400, 200);
    frame.getContentPane().setLayout(null);
    progressBar_1 = new JProgressBar();
    progressBar_1.setBounds(102, 40, 150, 16);
    frame.getContentPane().add(progressBar_1);
    progressBar_1.setStringPainted(true);
    frame.setVisible(true);
}
public void redfile()
{
    try{
    String s="";
    File f1=new File("sample.txt");
    FileReader fr=new FileReader(f1);
    BufferedReader br=new BufferedReader(fr);
    Task t=new Task();
    t.start();
    while((s=br.readLine())!=null){
                                                                                           try{Thread.sleep(200);}catch(Exception e){
        }
        System.out.println("-->"+s);
    }
    }catch(Exception e){
    }
}
private class Task extends Thread
{
    public void run()
    {
        for(int j=0;j<=100; j+=5)
        {
            progressBar_1.setValue(j);
        }
        try {
           Thread.sleep(100);
        } catch (InterruptedException e) {}
    }
}

    }

1 个答案:

答案 0 :(得分:4)

您不需要任何线程来更新进度条状态。您知道文件中存在的总字节数。只需根据读取的字节数计算完成的百分比。

public void redfile() {
    try {
        ...

        long totalLength = f1.length();
        double lengthPerPercent = 100.0 / totalLength;
        long readLength = 0;
        System.out.println(totalLength);
        while ((s = br.readLine()) != null) {
            readLength += s.length();
            progressBar_1.setValue((int) Math.round(lengthPerPercent * readLength));
            ...
        }
        progressBar_1.setValue(100);
        fr.close();

    } catch (Exception e) {
         ...
    }
}