好的,我有一个程序:
- 创建一个临时文件基于 用户输入
- 打印文件(可选)
- 删除文件(可选)
我的问题在阶段 2 和阶段 3 之间,我需要等待文件完成打印,直到我可以删除它。
仅供引用:打印需要 5-10 分钟(大文件在旧计算机上假脱机)
所以我需要从 Java 中检查是否:
默认打印队列为空
文件正在使用中(注意:打印时 File.canWrite() 返回 true)
最佳答案
您检查过 Java Print API 了吗?来自 http://download.oracle.com/javase/1.4.2/docs/api/javax/print/event/PrintJobListener.html :
public interface
PrintJobListener
Implementations of this listener interface should be attached to a DocPrintJob to monitor the status of the printer job.
我想你可以提交一个打印作业,然后通过它监控它的状态。
中还有一个相当完整的示例(注意:URL 似乎已经改变,并指向潜在的恶意软件)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) {
}
}
}
关于Java - 检查文件是否在打印队列/正在使用中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3687184/