我想停止通过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);
}
});
在调试程序时,取消消息不会打印在控制台中,这意味着每当我点击取消按钮并且仍然使用成功消息创建输出文件时,任务不会被取消。我怎么能阻止这个呢?有什么帮助吗?
答案 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;您自己的方法(cancel
为final
:P)我无法保证由于调用cancel
本身而触发任何属性更改事件。
工作人员需要维护对doInBackground
方法创建的提取器的引用,以允许它在提取器中成功触发取消