我想停止通过 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);
}
});
在调试程序时,取消消息不会打印在控制台中,这意味着每当我点击取消按钮时任务都不会被取消,并且仍然使用成功消息创建输出文件。我怎样才能阻止这个呢?有什么帮助吗?
最佳答案
基本上,您的 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
中,您需要提供某种自己的“停止”方法(因为 cancel
是 final
: P) 并且我不能保证会因为调用 cancel
本身而触发任何属性更改事件。
工作线程需要维护对由 doInBackground
方法创建的提取器的引用,以允许其成功触发提取器中的取消
关于java - 取消/强制停止通过 SwingWorker 执行的输入和输出流,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41646876/