如何在读取文本文件时使用Java进度条? [英] How to use Java progress bar while read a text file?

查看:161
本文介绍了如何在读取文本文件时使用Java进度条?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am new to java swing, I want to read the text file. while reading that file i want to display the percentage of readed lines in java progress bar. Any sample code is welcome. i tried but i don't know whether my logic is correct or not. How can i acheive this.

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) {}
    }
}

    }


推荐答案

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

You don't need any Thread to update the progress bar status. You know the total no of bytes present in the file. Just calculate the percent done on the basis of bytes read.

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) {
         ...
    }
}

这篇关于如何在读取文本文件时使用Java进度条?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆