好的,我有一个程序:
- 根据用户输入创建临时文件
- 打印文件(可选)
- 删除文件(可选)
我的问题出现在第二和第三阶段之间,我需要等待文件打印完成后才能删除它。
提醒一下:打印需要5-10分钟(在旧计算机上处理大型文件)。
因此,我需要从Java中能够检查:
默认的打印队列是否为空
文件是否正在使用(注意:File.canWrite()返回true表示正在打印)
exampledepot.com/egs/javax.print/WaitForDone.html:
try {
// Open the image file
InputStream is = new BufferedInputStream(
new FileInputStream("filename.gif"));
// Create the print job
DocPrintJob job = service.createPrintJob();
Doc doc = new SimpleDoc(is, flavor, null);
// Monitor print job events
PrintJobWatcher pjDone = new PrintJobWatcher(job);
// Print it
job.print(doc, null);
// Wait for the print job to be done
pjDone.waitForDone();
// It is now safe to close the input stream
is.close();
} catch (PrintException e) {
} catch (IOException e) {
}
class PrintJobWatcher {
// true iff it is safe to close the print job's input stream
boolean done = false;
PrintJobWatcher(DocPrintJob job) {
// Add a listener to the print job
job.addPrintJobListener(new PrintJobAdapter() {
public void printJobCanceled(PrintJobEvent pje) {
allDone();
}
public void printJobCompleted(PrintJobEvent pje) {
allDone();
}
public void printJobFailed(PrintJobEvent pje) {
allDone();
}
public void printJobNoMoreEvents(PrintJobEvent pje) {
allDone();
}
void allDone() {
synchronized (PrintJobWatcher.this) {
done = true;
PrintJobWatcher.this.notify();
}
}
});
}
public synchronized void waitForDone() {
try {
while (!done) {
wait();
}
} catch (InterruptedException e) {
}
}
}