流的进度监视器

时间:2013-04-09 17:32:13

标签: java stream progress

我已经创建了从客户端到服务器的流。对于这段代码,如何为此类创建ProgressMonitorInputStream或其他内容?

        FileInputStream fileStream = new FileInputStream(file);
        int ch;
        do
        {
            ch = fileStream.read();
            exitStream.writeUTF(String.valueOf(ch));
        }
        while(ch != -1);
        fileStream.close();

更新的代码 - 窗口出现,但它是空的。只有一个框架。如何解决?

         String fileName = "aaa.jpg";
         File fileToBeSend = new File(fileName);

         InputStream input = new ProgressMonitorInputStream(
         null, 
         "Reading: " + fileName, 
         new FileInputStream(fileToBeSend));

         int ch;
         do 
         {
             ch = input.read();
            exitStream.writeUTF(String.valueOf(ch)); 
         } while(ch != -1);

         input.close();

2 个答案:

答案 0 :(得分:1)

要使ProgressMonitorInputStream正常工作,您需要阅读非常大的文件。在其文件中指明:

  

这会创建一个进度监视器来监视读取的进度   输入流。 如果需要一段时间,则会弹出ProgressDialog   最多通知用户。如果用户点击取消按钮a   下次读取时将抛出InterruptedIOException。好吧   流关闭时完成清理。

这是一个例子。确保输入的文件(bigFile.txt)包含许多要阅读的内容。

enter image description here

import java.awt.Color;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.InputStreamReader;

import javax.swing.JLabel;
import javax.swing.ProgressMonitorInputStream;

public class ProgressMonitorInputStreamDemo {

  public static void main(String args[]) throws Exception {
  String file = "bigFile.txt";
  FileInputStream fis = new FileInputStream(file);
  JLabel filenameLabel = new JLabel(file, JLabel.RIGHT);
  filenameLabel.setForeground(Color.black);
  Object message[] = { "Reading:", filenameLabel };
  ProgressMonitorInputStream pmis = new ProgressMonitorInputStream(null, message, fis);
  InputStreamReader isr = new InputStreamReader(pmis);
  BufferedReader br = new BufferedReader(isr);
  String line;
  while ((line = br.readLine()) != null) {
    System.out.println(line);
  }
  br.close();
  }
}

注意: 如果您想查看ProgressBar,无论您阅读的文件多么小,都可以使用SwingWorker。请查看 this Post

答案 1 :(得分:1)

你只是说,如何使用嵌套流,这样的东西?

    ProgressMonitorInputStream input = new ProgressMonitorInputStream(
         null, 
         "Reading: " + file, 
         new FileInputStream(file));

    ProgressMonitor monitor = input.getProgressMonitor();
    // do some configuration for monitor here

    int ch;
    do {
        ch = input.read();
        // note: writing also the last -1 value
        exitStream.writeUTF(String.valueOf(ch)); 
    } while(ch != -1);

    input.close();
相关问题