-1

i want to send commands to to an embadded pc whihch connected to my pc through serial port ... here is the code that i use ...

public class Write {

static Enumeration portList;
static CommPortIdentifier portId;
static String messageString = "Hello, world!\n";
static SerialPort serialPort;
static OutputStream outputStream;

public static void main(String[] args) {
    portList = CommPortIdentifier.getPortIdentifiers();
    while (portList.hasMoreElements()) {
        portId = (CommPortIdentifier) portList.nextElement();
        if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL) {
            if (portId.getName().equals("COM1")) {
                try {
                    serialPort = (SerialPort) portId.open("SimpleWriteApp", 2000);
                    System.out.println("openning the port...");
                } catch (PortInUseException e) {
                }
                try {
                    outputStream = serialPort.getOutputStream();
                    System.out.println("sending the command...");
                } catch (IOException e) {
                }
                try {
                    serialPort.setSerialPortParams(9600,
                            SerialPort.DATABITS_8,
                            SerialPort.STOPBITS_1,
                            SerialPort.PARITY_NONE);

                } catch (UnsupportedCommOperationException e) {
                }
                try {
                    outputStream.write(messageString.getBytes());
                    serialPort.close();
                } catch (IOException e) {
                }
            }
        }
    }
}

}

is this code is correct, or there should be some modification to this code ....

4

1 回答 1

0

如果它有效,那么我可以看到没有任何明显错误!我要指出的唯一一件事是,将 close 语句(例如当您在末尾关闭串行端口时)放在 finally 块中是一种很好的做法,因此它们总是被执行(VM 终止除外。)目前如果方法抛出outputStream.write(messageString.getBytes());的异常close()不会被执行。

您也不应该忽略异常,至少printStackTrace()要确保没有发生任何事情。

于 2011-08-04T09:15:21.053 回答