Writing to a printer using OutputStream
Here's an example of how to write text to a printer using the
OutputStream classes. It simply opens the printer as if it
were a file (the printer name is system-dependent; on Windows
machines, it will be lpt1 or prn, while on unix machines, it
will be something like /dev/lp), then writes whatever text it has
to write, then writes a form feed and closes the file.
//class that opens the printer as a file and writes "Hello World" to it
import java.io.*;
public class lpt
{
public static void main (String[] argv)
{
//check for argument
if (argv.length != 1)
{
System.out.println("usage: java lpt1 ");
System.exit(0);
}
try
{
//open printer as if it were a file
FileOutputStream os = new FileOutputStream(argv[0]);
//wrap stream in "friendly" PrintStream
PrintStream ps = new PrintStream(os);
//print text here
ps.println("Hello world!");
//form feed -- this is important
//Without the form feed, the text
//will simply sit in the print
//buffer until something else
//gets printed.
ps.print("\f");
//flush buffer and close
ps.close();
}
catch (Exception e)
{
System.out.println("Exception occurred: " + e);
}
}
}