【问题标题】:Problem with printer in javajava中的打印机问题
【发布时间】:2011-09-02 20:59:46
【问题描述】:

我有一个问题,我想发送以在打印机上打印文件,为此我获得了我联网的打印机的 IP 地址并选择了第一个,这是代码:

PrintService[] service = PrinterJob.lookupPrintServices();// list of ip address 

PrinterJob printJob = PrinterJob.getPrinterJob();

printJob.setPrintService(service[0]);//I get the first address 

但是现在我想分配包含我想要的打印机的IP地址的字符串:\\10.100.20.26\My printer,而不是我拥有的网络,并且那里不知道如何,请有人帮助我,我已经搜索了解决方案,但我没有得到很好的结果。

【问题讨论】:

    标签: java printing ip ip-address printers


    【解决方案1】:
     public void printFile(File file, String printerIp) throws PrintException, IOException {
    
            Socket socket = new Socket(printerIp, 9100);
    
            FileInputStream fileInputStream = new FileInputStream(file);
            byte [] mybytearray  = new byte [(int)file.length()];
    
            fileInputStream.read(mybytearray,0,mybytearray.length);
    
            OutputStream outputStream = socket.getOutputStream();
    
            outputStream.write(mybytearray,0,mybytearray.length);
    
                 //Curious thing is that we have to wait some time to make more prints.
            try {
                Thread.sleep(500);
            } catch (InterruptedException e) {
    
            }
    
            outputStream.flush();
            outputStream.close();
            socket.close();
            fileInputStream.close();
        }
    
        //void main
          File f = new File("C:\\Users\\SHINWAR\\Desktop\\link.txt");
        try {
            printFile(f, "192.168.1.100"); //f : file to print , ip printer
        } catch (Exception e) {
            System.out.println(e + "--file");
        }
    

    从ip打印并发送文件.txt

    【讨论】:

      【解决方案2】:

      我猜PrintService 有一些属性可以给你它的路径。因此,请遍历 PrintServices 的数组,找到与您拥有的路径匹配的一个并使用它:

      PrintService[] services = PrinterJob.lookupPrintServices();// list of ip address
      String myPrinter = "10.100.20.26\My printer";
      PrintService serviceToUse = null;
      
      for (PrintService service: services) {
          if (service.getPath().equals(myPrinter)) {
              serviceToUse = service;
              break;
          }
      }
      
      if (serviceToUse != null) {
          PrinterJob printJob = PrinterJob.getPrinterJob();
      
          printJob.setPrintService(serviceToUse);
      }
      

      【讨论】:

      • Mmmm....我想添加一个新的 IP 地址,而不是来自服务列表,因为我有一个 String myPrinter = "10.100.20.26\My printer";但我不知道如何打印到该 IP 地址
      猜你喜欢
      • 1970-01-01
      • 2018-06-27
      • 1970-01-01
      • 2011-08-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多