如何在Java中使用.readLine()跟踪文件的读取? [英] How do I track reading of a a file using .readLine() in java?

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

问题描述

我正在使用bufferedREader读取文件,该文件是一个文本很多的文本文件

I am reading a file using bufferedREader ,the file is a text file with lot of text

这是我的读取方式

 while(true)  //I know the loop is not perfect just ignore it for now, i wanna concentrate on the tracking
                {
                      try
                      {
                       br.readLine();
                      }
                      catch(IOException e)
                      {
                      break;
                      }
                      catch (Exception e)
                      {
                      break;
                      }
                }

我想跟踪我拥有的文件百分比读取,这样我就可以在进度条中使用该百分比值,例如:

I want to track what percentage of the file I have read so I can use that percentage value in my progress bar like this:

while(true)
                {
                      try
                      {
                       br.readLine();
                       progressBar.setValue(percentageRead);//how do I get percentageRead value dynamically?
                      }
                      catch(IOException e)
                      {
                      break;
                      }
                      catch (Exception e)
                      {
                      break;
                      }
                }


推荐答案

有有很多方法可以实现这一目标,但是您需要牢记四件事...

There are any number ways to achieve this, but you need to keep four things in mind...


  1. 您需要知道您有多少阅读

  2. 您需要知道已经阅读了多少

  3. 您永远不要在可能会阻止它的事件调度线程的上下文中执行任何操作(例如长时间运行的循环或阻塞的I / O)

  4. 除了事件调度线程之外,请勿从任何线程修改或更改UI的状态

  1. You need to know how much you are reading
  2. You need to know how much you have read
  3. You should never performing any action within context of the Event Dispatching Thread that might block it (such as long running loops or blocking I/O)
  4. You should never modify or change the state of the UI from any thread other then the Event Dispatching Thread

此示例仅使用 SwingWorker 在后台线程中读取文件,并使用其进度功能发布更新返回到EDT的上下文。

This example simply uses a SwingWorker to read the file in a background thread and uses it's progress functionality to post updates back to the context of the EDT.

import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.GridBagLayout;
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 java.util.concurrent.ExecutionException;
import javax.swing.JFrame;
import javax.swing.JProgressBar;
import javax.swing.SwingWorker;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

public class ReadFile {

    public static void main(String[] args) {
        new ReadFile();
    }

    public ReadFile() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                }

                final JProgressBar pb = new JProgressBar(0, 100);
                final ReadFileWorker worker = new ReadFileWorker();
                worker.addPropertyChangeListener(new PropertyChangeListener() {
                    @Override
                    public void propertyChange(PropertyChangeEvent evt) {
                        if ("progress".equalsIgnoreCase(evt.getPropertyName())) {
                            pb.setValue(worker.getProgress());
                        }
                    }
                });

                JFrame frame = new JFrame("Testing");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.setLayout(new GridBagLayout());
                frame.add(pb);
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);

                worker.execute();
            }
        });
    }

    public class ReadFileWorker extends SwingWorker<List<String>, String> {

        @Override
        protected List<String> doInBackground() throws Exception {
            List<String> lines = new ArrayList<>(25);
            File textFile = new File("Test.txt");
            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;
                String lastText = "";
                while ((bytesRead = is.read(content)) != -1) {

                    totalBytes += bytesRead;
                    setProgress(Math.round(((float) totalBytes / (float) byteLength) * 100f));

                    String text = lastText + new String(content);
                    boolean keepEnd = !text.endsWith("\n");
                    String[] parts = text.split("\n");

                    for (int count = 0; count < (keepEnd ? parts.length - 1 : parts.length); count++) {
                        lines.add(parts[count]);
                        publish(parts[count]);
                    }

                    if (keepEnd) {
                        lastText = parts[parts.length - 1];
                    } else {
                        lastText = "";
                    }

                    // This is only here to slow the demonstration down
                    Thread.sleep(5);

                }

                System.out.println("Read " + totalBytes + " bytes...");
                System.out.println("Read " + lines.size() + " lines...");

            } finally {

            }

            return lines;
        }

        @Override
        protected void done() {
            try {
                List<String> lines = get();
            } catch (InterruptedException | ExecutionException ex) {
                ex.printStackTrace();
            }
        }

    }

}

现在,您还可以将 SwingWorker 与其他 ProgressInputStream实现之一合并。看看 Swing中的并发以了解更多详细信息

Now, you could incorporate the SwingWorker with one of the other "ProgressInputStream" implementations as well. Take a look at Concurrency in Swing for more details

这篇关于如何在Java中使用.readLine()跟踪文件的读取?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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