Java如何获得默认的打印服务(打印机)?

要查找默认的打印服务,我们可以使用javax.print.PrintServiceLookupclasslookupDefaultPrintService()方法。

package org.nhooo.example.print;

import javax.print.PrintService;
import javax.print.PrintServiceLookup;

public class GetPrinter {
    public static void main(String[] args) {
        //获取此环境的默认打印服务。当返回null 
        // 找不到默认的打印服务。
        PrintService service = PrintServiceLookup.lookupDefaultPrintService();
        if (service != null) {
            String printServiceName = service.getName();
            System.out.println("Print Service Name = " + printServiceName);
        } else {
            System.out.println("No default print service found.");
        }
    }
}

上面的代码片段的结果:

Print Service Name = HP LaserJet P1005