文本文件打印Java Applet在Windows操作系统中不起作用

时间:2013-10-25 10:07:56

标签: java applet

我创建了一个java applet,用于将文本文件内容从远程位置复制到本地计算机。它工作正常,并尝试使用DOS命令(Windows XP)进行打印。它不起作用,但它在Ubuntu OS中运行良好。你能帮我改进我的代码吗?

这是我的代码

try {
            String server=this.getParameter("SERVER");
            String filename=this.getParameter("FILENAME");

            String osname=System.getProperty("os.name");
            String filePath="";

            URL url = new URL("http://10.162.26.8/openLypsaa/reports/report_oc/127.0.0.1_sys_ANN_milkbill");
            URLConnection connection = url.openConnection();
            InputStream is = connection.getInputStream();

            if("Linux".equals(osname))
            {
                filePath = "/tmp/OLFile";
            }
            else
            {
                filePath = "C:/WINDOWS/Temp/OLFile";

            }

            OutputStream output = new FileOutputStream(filePath);

            byte[] buffer = new byte[256];
            int bytesRead = 0;
            while ((bytesRead = is.read(buffer)) != -1)
            {
                System.out.println(bytesRead);
                output.write(buffer, 0, bytesRead);
            }
            output.close();

    if("Linux".equals(osname))
                Runtime.getRuntime().exec("lp /tmp/OLFile").waitFor();
            else
                Runtime.getRuntime().exec("print C:/WINDOWS/Temp/OLFile").waitFor();
         }

2 个答案:

答案 0 :(得分:1)

在Windows中,您希望使用:filePath = "C:\\WINDOWS\\Temp\\OLFile";

Runtime.getRuntime().exec("print C:\\WINDOWS\\Temp\\OLFile").waitFor();

您还可以谷歌了解PathSeparator

答案 1 :(得分:1)

您可以使用可在每个平台上使用的java打印服务。此代码段将您的打印件发送到默认打印机。

public static void main(String[] args) {                
    FileInputStream textStream;
    try 
    {
        textStream = new FileInputStream("D:\\email_addresses.txt");
        DocFlavor myFormat = DocFlavor.INPUT_STREAM.AUTOSENSE;
        Doc myDoc = new SimpleDoc(textStream, myFormat, null); 

        PrintRequestAttributeSet aset = new HashPrintRequestAttributeSet(); 

        aset.add(new Copies(1)); 
        aset.add(Sides.ONE_SIDED); 

        PrintService printService = PrintServiceLookup.lookupDefaultPrintService();

        System.out.println("Printing to default printer: " + printService.getName());

        DocPrintJob job = printService.createPrintJob();
        job.print(myDoc, aset);

    } catch (FileNotFoundException e1) {
        e1.printStackTrace();
    } catch (PrintException e) {
        e.printStackTrace();
    } 
}