在网上找了一下Java 文件打印功能,现记下来:
1. 不弹出选择框,直接打印
public class Printting {
   public static void main(String[] args) {

    File file =     new File( "d://xh.txt");
    
    //构建打印请求属性集
    PrintRequestAttributeSet pras = new HashPrintRequestAttributeSet();  
    
    //设置打印格式
    DocFlavor flavor = DocFlavor.INPUT_STREAM.AUTOSENSE;          
    
    //查找所有的可用的打印服务    
    PrintService printService[] = PrintServiceLookup.lookupPrintServices(flavor, pras);   
    
    
    //如果找到打印机
    if( printService.length > 0 ){
      
      DocPrintJob job = printService[0].createPrintJob();
      FileInputStream fis = null;
      try {
        
        fis = new FileInputStream(file);
        //构建文件属性
        DocAttributeSet das = new HashDocAttributeSet();
        Doc doc = new SimpleDoc(fis, flavor, das);
        job.print(doc, pras);
        
      } catch (FileNotFoundException e) {
        e.printStackTrace();
      } catch (PrintException e) {
        e.printStackTrace();
      } //end try

    }//end if

}


2.弹出选择打印机对话框
public class Printting {

   public static void main(String[] args) {
    File file =     new File( "d://xh.txt");
    
    //构建打印请求属性集
    PrintRequestAttributeSet pras = new HashPrintRequestAttributeSet();  
    
    //设置打印格式
    DocFlavor flavor = DocFlavor.INPUT_STREAM.AUTOSENSE;          
    
    //查找所有的可用的打印服务    
    PrintService printService[] = PrintServiceLookup.lookupPrintServices(flavor, pras);
    
    //定义默认的打印服务(PrintService)
    PrintService defaultService = PrintServiceLookup.lookupDefaultPrintService();
    
    //显示打印对话框
    PrintService service = ServiceUI.printDialog(null, 200, 200,
        printService, defaultService, flavor, pras);
    
    if( service != null ){
      
      try {
        //创建打印作业
        DocPrintJob job = service.createPrintJob();    
        //构建文件打印流
        FileInputStream fis = new FileInputStream(file);
        //构建文件属性
        DocAttributeSet das = new HashDocAttributeSet();
        
        Doc doc = new SimpleDoc(fis, flavor, das);
        
        job.print(doc, pras);
      } catch (FileNotFoundException e) {
        e.printStackTrace();
      } catch (PrintException e) {
        e.printStackTrace();
      }//end try
      
    }//end if

  }//end class

}