如何在IO操作期间显示进度

时间:2012-10-20 22:53:00

标签: java file-io progress

我想从数组中读取元素并将读取的进度显示为并行进程读取。

我有两个内部课程:

public class NumbersCounter {

    int totalCountOfLines;
    int currentCountOfLines = 1;

    public NumbersCounter() throws FileNotFoundException, IOException {    
        new Read();
        new Progress();
    }

    public static void main(String[] args) {
        try {
            new NumbersCounter();
        } catch (FileNotFoundException ex) {
            Logger.getLogger(NumbersCounter.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(NumbersCounter.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    class Progress extends Thread {  
        public Progress() {
            start();
        }

        @Override
        public void run() {        
            synchronized(new Object()) {
                while (currentCountOfLines <= totalCountOfLines) {
                    System.out.println(currentCountOfLines / totalCountOfLines * 100 + "%");
                    Thread.yield();
                }            
            }
    }}

    class Read extends Thread {
        private FileHandler fh = new FileHandler("ololo.txt");
        private String[] lines;

        public Read() throws FileNotFoundException, IOException {
            this.lines = fh.readFromFile();
            start();
        }

        @Override
        public void run() {

            totalCountOfLines = this.lines.length;

            if (totalCountOfLines > 0) {
                synchronized(new Object()) {
                    for (String line : lines) {
                        currentCountOfLines++;   
                        Thread.yield();
                    }

                }
            } else {
                totalCountOfLines = 0;
            }    
        }
    }
}

当执行Read Thread的第一步时,我需要执行Progress线程,然后执行Read,然后执行Progress。

2 个答案:

答案 0 :(得分:1)

使用javax.swing.ProgressMonitorInputStream类作为输入流的包装器,显示进度的对话框。

答案 1 :(得分:0)

请参阅有关java.util.concurrent包的文档。

http://docs.oracle.com/javase/1.5.0/docs/api/java/util/concurrent/package-summary.html

具体是ExecutorService,Executor,Callable和Future接口。并发包是为了做你想做的事情而构建的,而不需要自己处理锁定和并发。

后台IO操作 - 逐步更新UI。