#10: Java can't talk to the serial and parallel ports

The Java Communications API is a very straight-forward API to talk to the serial and parallel ports.

import javax.comm.*;
import java.util.*;
import java.io.*;


public class PortTyper {

  public static void main(String[] args) {

    if (args.length < 1) {
      System.out.println("Usage: java PortTyper portName");
      return;
    }

    try {    
      CommPortIdentifier com = 
       CommPortIdentifier.getPortIdentifier(args[0]);
      CommPort thePort  = com.open("PortOpener", 10);
      CopyThread input = 
       new CopyThread(System.in, thePort.getOutputStream());
      CopyThread output = 
       new CopyThread(thePort.getInputStream(), System.out);
      input.start();
      output.start();

    }
    catch (Exception e) {
      System.out.println(e);
    }

  }

}

class CopyThread extends Thread {

  InputStream theInput;
  OutputStream theOutput;

  CopyThread(InputStream in) {
    this(in, System.out);
  }

  CopyThread(OutputStream out) {
    this(System.in, out);
  }

  CopyThread(InputStream in, OutputStream out) {
    theInput = in;
    theOutput = out;
  }

  public void run() {

    try {
      byte[] buffer = new byte[256];
      while (true) {
        int bytesRead = theInput.read(buffer);
        if (bytesRead == -1) break;
        theOutput.write(buffer, 0, bytesRead);
      }
    }
    catch (IOException e) {
      System.err.println(e);
    }

  }

}
Still need


Previous | Next | Top
Other Presentations | Cafe au Lait Home
Last Modified May 16, 1999
Copyright 1999 Elliotte Rusty Harold
elharo@metalab.unc.edu