取消/强制停止通过SwingWorker执行的输入和输出流

时间:2017-01-14 04:46:25

标签: java swingworker

我想停止通过SwingWorker doInBackground执行的输入和输出流。每当我取消任务时,它仍然会创建文件(请参阅下面的代码)。任务很简单,"对于指定的每个文件名(一个String),输出具有给定名称的文件" (类似的东西)。

我在一个单独的包/类中编写了IO流。所以代码就像:

public class ResourceFileExtract(String outputFile) {
  InputStream inputStream = null;
  OutputStream outputStream = null;
  try {
    inputStream = getClass().getResourceAsStream("/resources/someFile");
    outputStream = new FileOutputStream(outputFile);
    byte[] bytes = new byte[1024];
    int numbers;
    while ((numbers = inputStream.read(bytes)) > 1) {
      outputStream.write(bytes, 0, length)
    }
    outputStream.flush();
    outputStream.close();
    inputStream.close();
  } /* Other codes here */
}

SwingWorker设置。

private class BackgroundTask extends SwingWorker<Integer, String> {
  @Override
  protected Integer doInBackground() {
    /* Some codes here */
    if (!isCancelled()) {
       for (/* Loop statement */) {
         try {
           // Input and Output stream called from a class...
           ResourceFileExtract fileExtract = new ResourceFileExtract(specifiedOutputName);
           System.out.println("Done (file extracted successfully)");
         } catch (IOException ex) {
           System.out.println("Error (unable to read resource file)");
           return 0;
         }
       }
    } else {
      // These texts are not printed in console...
      System.out.println("Cancelled (I/O streaming stopped)");
      return 0;
    }
    return 0;
  }
}

使用以下命令执行SwingWorker:

JButton start = new JButton("Start");
start.addActionListener(new ActionListener() {
  @Override
  public void actionPerformed(ActionEvent evt) {
    BackgroundTask bgTask = new BackgroundTask();
    bgTask.execute();
  }
});

并取消:

JButton stop = new JButton("Stop");
stop.addActionListener(new ActionListener() {
  @Override
  public void actionPerformed(ActionEvent evt) {
    bgTask.cancel(true);
  }
});

在调试程序时,取消消息不会打印在控制台中,这意味着每当我点击取消按钮并且仍然使用成功消息创建输出文件时,任务不会被取消。我怎么能阻止这个呢?有什么帮助吗?

1 个答案:

答案 0 :(得分:3)

基本上,您的ResourceFileExtract课程需要取消,例如......

public class ResourceFileExtract {

    private String outputFile;
    private AtomicBoolean cancelled = new AtomicBoolean(false);

    public ResourceFileExtract(String outputFile) {
        this.outputFile = outputFile;
    }

    public void cancel() {
        cancelled.set(true);
    }

    public void extract() throws IOException {

        try (InputStream inputStream = getClass().getResourceAsStream("/resources/someFile");
                 OutputStream outputStream = new FileOutputStream(outputFile)) {
            byte[] bytes = new byte[1024];
            int numbers;
            while (!cancelled.get() && (numbers = inputStream.read(bytes)) > 1) {
                outputStream.write(bytes, 0, numbers);
            }
        } catch (IOException exp) {
            throw exp;
        }
    }
}

然后在您的SwingWorker中,您需要提供一些&#34;停止&#34;您自己的方法(cancelfinal:P)我无法保证由于调用cancel本身而触发任何属性更改事件。

工作人员需要维护对doInBackground方法创建的提取器的引用,以允许它在提取器中成功触发取消