Java - 检查文件是否在打印队列/正在使用中

标签 java file printing locking

好的,我有一个程序:

  1. 创建一个临时文件基于 用户输入
  2. 打印文件(可选)
  3. 删除文件(可选)

我的问题在阶段 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.

我想你可以提交一个打印作业,然后通过它监控它的状态。

exampledepot.com/egs/javax.print/WaitForDone.html: 中还有一个相当完整的示例(注意:URL 似乎已经改变,并指向潜在的恶意软件)

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/

相关文章:

python - String.strip() 重要性

java - 将服务器上存储的pdf文件打印到客户端打印机

python - 为什么在终端和运行终端的程序中内联打印转义的十六进制字符之间存在差异?

python - 很难检测到空列表

java - 如果我的 .txt 文件为空,如何修复扫描仪错误?

json - 将 JSON 结构附加到 JSON 文件 Golang

java - 需要帮助解决 webdriver 中的问题(无法在 PATH 中找到 firefox 二进制文件。请确保已安装 firefox。)

java - 为什么 String 方法 substring() 不是 Java 中的驼峰命名法?

java - 保持敏锐的 GUI 开发技能

java - 从一个线程检索值到另一线程