2013/03/30

Java 取得Com Port

下個禮拜國科會Demo東西會用到COM Port的東西,去Google查詢後大概就只有Java Communications API可以用了;不然就自己寫吧XD

這個API應該也是透過JNI的方式調用C去取得的,Java是透過虛擬環境執行的,所以應該沒有原生API吧

不過要使用這個API可以參考『Java Comm API』,這篇文章雖然還蠻久了;不過有提供載點就是了

我下載的版本是2.0,1998年寫得






官網安裝說明講得很清楚
Copy win32com.dll to your <JDK>\bin directory. 
Copy comm.jar to your <JDK>\lib directory. 
Copy javax.comm.properties to your <JDK>\lib directory. 

The javax.comm.properties file must be installed. If it is not, no ports will be found by the system. 
Add comm.jar to your classpath (do not do this step for a JRE installation).
If you don't have a classpath defined: 

C:\>set CLASSPATH=c:\jdk1.1.6\lib\comm.jar 

If you already have a classpath defined: 

C:\>set CLASSPATH=c:\jdk1.1.6\lib\comm.jar;%classpath%

Several serial port sample applications are provided with this release. One of them is BlackBox. To run BlackBox, first add BlackBox.jar to your classpath: 

C:\>set CLASSPATH=c:\commapi\samples\Blackbox\BlackBox.jar;%CLASSPATH% 

不過當可以執行的時候可能會碰到完全沒有顯示的狀況

這時候就照著以下做就可以解決了
Copy comm.jar to your <JRE>\lib\ext.
Copy javax.comm.properties to your <JRE>\lib. 




import java.util.Enumeration;

import javax.comm.CommPortIdentifier;

public class ComPort {
    public static void main(String[] args) {
        Enumeration portList = CommPortIdentifier.getPortIdentifiers();
        while (portList.hasMoreElements()) {
            CommPortIdentifier port = (CommPortIdentifier) portList
                    .nextElement();
            if (port.getPortType() == CommPortIdentifier.PORT_SERIAL) {
                System.out.println(port.getName() + " SERIAL");
            } else if (port.getPortType() == CommPortIdentifier.PORT_PARALLEL) {
                System.out.println(port.getName() + " PARALLEL");
            }
        }
    }
}



參考資料:
http://www.oracle.com/technetwork/java/index-jsp-141752.html
http://jingjong404.blogspot.tw/2008/05/java-serial-port.html
http://docs.oracle.com/cd/E17802_01/products/products/javacomm/reference/api/javax/comm/package-summary.html
http://www.javaworld.com.tw/jute/post/view?bid=29&id=66063&sty=1&tpg=2&age=-1
http://stackoverflow.com/questions/3959743/problem-of-using-the-javax-comm-api-on-windows-7
http://f953024.pixnet.net/blog/post/25852309
http://stackoverflow.com/questions/900950/how-to-send-data-to-com-port-using-java