我应该做一个简单的任务:用Java打印文本文件,但是虽然代码执行没有错误,但实际上没有任何内容来自打印机。我检查了打印队列并且它们已经空了。我在Windows 10上使用Java 8.
我已经尝试了很多代码来让事情顺利进行,但这就是我最终的结果。这可能都是本地问题,但也许有人可以在我的代码中发现错误或可疑的东西。
package net.snortum.play;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import javax.print.Doc;
import javax.print.DocFlavor;
import javax.print.DocPrintJob;
import javax.print.PrintException;
import javax.print.PrintService;
import javax.print.PrintServiceLookup;
import javax.print.ServiceUI;
import javax.print.SimpleDoc;
import javax.print.attribute.DocAttributeSet;
import javax.print.attribute.HashDocAttributeSet;
import javax.print.attribute.HashPrintRequestAttributeSet;
import javax.print.attribute.PrintRequestAttributeSet;
import javax.print.attribute.standard.MediaSizeName;
public class PrinterPlay {
public static void main(String[] args) {
new PrinterPlay().run();
}
private void run() {
String filename = "src/net/snortum/play/PrinterPlay.java";
PrintRequestAttributeSet pras = new HashPrintRequestAttributeSet();
DocFlavor flavor = DocFlavor.INPUT_STREAM.AUTOSENSE;
PrintService printService[] = PrintServiceLookup
.lookupPrintServices(flavor, pras);
if (printService == null || printService.length == 0) {
System.out.println("No printer could be found");
return;
}
try {
PrintService defaultService = PrintServiceLookup
.lookupDefaultPrintService();
PrintService service = ServiceUI.printDialog(null, 200, 200,
printService, defaultService, flavor, pras);
if (service == null) {
System.out.println("Printing canceled");
return;
}
System.out.println(service.getName());
DocPrintJob job = service.createPrintJob();
FileInputStream fis = new FileInputStream(filename);
DocAttributeSet das = new HashDocAttributeSet();
das.add(MediaSizeName.NA_LETTER);
Doc doc = new SimpleDoc(fis, flavor, das);
job.print(doc, pras);
System.out.println("Print job sent without exception");
} catch (PrintException pe) {
System.out.println("Problem printing");
pe.printStackTrace();
} catch (FileNotFoundException fnfe) {
System.out.println("Can't find file");
fnfe.printStackTrace();
}
}
}
我尝试了什么以及发生了什么: