
i used a coding for getting data from serial port. JOptionbox with "port not found" message is shown when i execute thru jar file. but when i execute thru netbeans, data is received from comm port. why it is happening? i attached the coding i used.
public class SimpleRead implements Runnable, SerialPortEventListener { static CommPortIdentifier portId; static Enumeration portList; InputStream inputStream; SerialPort serialPort; Thread readThread; public static void main(String[] args) { boolean portFound = false; String defaultPort = "COM2";
if (args.length > 0) {
defaultPort = args[0];
}
portList = CommPortIdentifier.getPortIdentifiers();
while (portList.hasMoreElements()) {
portId = (CommPortIdentifier) portList.nextElement();
if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL) {
if (portId.getName().equals(defaultPort)) {
JOptionPane.showMessageDialog("Found port: "+defaultPort);
portFound = true;
SimpleRead reader = new SimpleRead();
}
}
}
if (!portFound) {
JOptionPane.showMessageDialog("port " + defaultPort + " not found.");
}
}
private int numBytes;
private String s;
public SimpleRead() {
try {
serialPort = (SerialPort) portId.open("SimpleReadApp", 2000);
} catch (PortInUseException e) {
System.out.println("port in use");
}
try {
System.out.println("Getting input Stream");
inputStream = serialPort.getInputStream();
} catch (IOException e) {
System.out.println(e);
}
try {
serialPort.addEventListener(this);
} catch (TooManyListenersException e) {
System.out.println(e);
}
serialPort.notifyOnDataAvailable(true);
try {
serialPort.setSerialPortParams(9600, SerialPort.DATABITS_8,
SerialPort.STOPBITS_1,
SerialPort.PARITY_NONE);
} catch (UnsupportedCommOperationException e) {}
readThread = new Thread(this);
readThread.start();
}
public void run() {
try {
Thread.sleep(2000);
} catch (InterruptedException e) {}
}
public void serialEvent(SerialPortEvent event) {
switch (event.getEventType()) {
case SerialPortEvent.BI:
case SerialPortEvent.OE:
case SerialPortEvent.FE:
case SerialPortEvent.PE:
case SerialPortEvent.CD:
case SerialPortEvent.CTS:
case SerialPortEvent.DSR:
case SerialPortEvent.RI:
case SerialPortEvent.OUTPUT_BUFFER_EMPTY:
break;
case SerialPortEvent.DATA_AVAILABLE:
byte[] readBuffer = new byte[8];
byte[] readBuffer2=null;
try {
while (inputStream.available() > 0) {
numBytes = inputStream.read(readBuffer);
readBuffer2= new byte[numBytes];
for(int i=0;i<numBytes;i++)
readBuffer2[i]=readBuffer[i];
}
s = new String(readBuffer2);
System.out.println("readbuffer......"+ s);
} catch (IOException e) {}
break;
}
}
}