我正在编写一个代码,它应该在客户端机器上找到打印机列表并设置一个特定的打印机来打印一个文档。但是我在网上看了一下,发现一些代码是这样的:
package org.ui;
import java.io.FileInputStream;
import javax.print.*;
import javax.print.attribute.HashPrintRequestAttributeSet;
import javax.print.attribute.PrintRequestAttributeSet;
public class Printing {
public static void main (String [] args) {
DocFlavor flavor = DocFlavor.INPUT_STREAM.AUTOSENSE;
PrintRequestAttributeSet aset = new HashPrintRequestAttributeSet ();
PrintService [] pservices = PrintServiceLookup.lookupPrintServices (flavor, aset);
try {
int printer = getPrinter(pservices);
if(printer == -1) {
throw new Exception("No network printer found");
}
DocPrintJob pj = pservices[0].createPrintJob();
FileInputStream fis = new FileInputStream ("c:///file.txt");
Doc doc = new SimpleDoc (fis, flavor, null);
pj.print (doc, aset);
}
catch (Exception ex) {
ex.printStackTrace ();
}
}
private static int getPrinter(PrintService[] pservices) {
int printer = -1;
for(int i = 0; i<pservices.length; i++) {
if(pservices[i].getName().contains("\\\\")) {
System.out.println("network printer: " + pservices[i].toString());
printer = i;
break;
}
}
return printer;
}
}
但是我无法在纸上打印,谁能告诉我这段代码有什么问题?它是一个桌面应用程序。