简体   繁体   English

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

[英]How to use Java progress bar while read a text file?

I am new to java swing, I want to read the text file. 我是java swing的新手,我想读取文本文件。 while reading that file i want to display the percentage of readed lines in java progress bar. 在读取该文件时,我想在java进度条中显示已读取行的百分比。 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) {
         ...
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM