如何使用Java检测打印机是否连接到您的计算机?

我正在使用swing Java创建一个GUI。 我必须使用一个按钮“打印”,它将直接开始打印我设置的文件而不打开默认的打印对话框。 我必须首先检查打印机是否连接到我的电脑?

可能正在使用PrintServiceLookup ?

此类的实现为特定类型的打印服务(通常等同于打印机)提供查找服务。

DocFlavor flavor = DocFlavor.INPUT_STREAM.POSTSCRIPT; PrintRequestAttributeSet aset = new HashPrintRequestHashAttributeSet(); aset.add(MediaSizeName.ISO_A4); PrintService[] pservices =PrintServiceLookup.lookupPrintServices(flavor, aset); if (pservices.length > 0) { DocPrintJob pj = pservices[0].createPrintJob(); //.... } 

注意:如果有打印机,PrintService的数量应该至少为1。 如果有实际的打印机,可能至少为2,因为您可以在计算机上安装纯软件打印机。 另见这个主题 。

根据平台和jdk,它可能有一些错误 ,但除此之外,以下方法应该至少列出打印机:

 import java.awt.print.*; import javax.print.*; import javax.print.attribute.*; import java.text.*; import javax.print.attribute.standard.*; public class ShowPrinters { public ShowPrinters() { } public static void main(String[] args) { DocFlavor myFormat = DocFlavor.SERVICE_FORMATTED.PRINTABLE; PrintRequestAttributeSet aset = new HashPrintRequestAttributeSet(); PrintService[] services =PrintServiceLookup.lookupPrintServices(myFormat, aset); System.out.println("The following printers are available"); for (int i=0;i 

在这个eclipse代码源中 ,您已经看到使用PrinterState来检查打印机是否实际连接:

 AttributeSet attributes = new HashPrintServiceAttributeSet( new PrinterName(printerName, Locale.getDefault())); PrintService[] services = PrintServiceLookup.lookupPrintServices( DocFlavor.SERVICE_FORMATTED.PRINTABLE, attributes); PrintService printService = services[0]; PrintServiceAttributeSet printServiceAttributes = printService.getAttributes(); PrinterState printerState = (PrinterState) printServiceAttributes.get(PrinterState.class); 

检查printerState是否为空。 注意:这可能并不总是足够(请参阅此主题 )。