我有以下例程,它是在windows中运行的usb4java应用程序接口中访问串行端口的入口点。任何想法都可能是错误的。
import javax.comm.*
public class SimpleJSComRead
public static void main(String[] args) {
portList = CommPortIdentifier.getPortIdentifiers();
if (portList.nextElement()==null) System.out.println("Is Null");
}}
同时,这可以使用jssc来工作。我可以通过这个接口读取有效数据。
import jssc.SerialPort;
import jssc.SerialPortException;
public class SimpleJSComRead {
public static void main(String[] args) {
SerialPort serialPort = new SerialPort("COM6");
try { serialPort.openPort();
} catch (SerialPortException e) {
e.printStackTrace();
}
if (serialPort.isOpened()) System.out.println("opened successfully");
try { serialPort.closePort();
} catch (SerialPortException e) {
e.printStackTrace();
}
}
}发布于 2018-09-14 00:45:14
我发现javax.comm库并不是完全的implemented或supported。我觉得奇怪的是,像从串口读取这样的基本功能对Java来说是一项困难的任务,而托管web应用程序却被各种API重复。我希望串行通信在Python和C++中得到很好的支持,因为它们更多地被科学界使用。
我发现的另一个解决方案是利用RXTX API...one和two。该过程包括下载压缩的发行版,并将dll和jar解压到FileSystem上的某个库站点。然后声明对Jar文件的依赖关系。例如在Gradle中
compile files( 'C:/..path../lib/jars/RXTXcomm.jar')。
设置dll库路径并加载dll
System.setProperty("java.library.path", "C:/..path../lib/dlls_x64")
System.loadLibrary("rxtxSerial")最后,串行接口不在javax.comm包中,而是在gnu.io包中。
import gnu.io.CommPortIdentifier
import io.FileMgr
//this one is based on RXTX and dlls are in library (gnu.io)
fun main(args: Array<String>) {
FileMgr.setDllLibraryPath("C:/..path../lib/dlls_x64")
System.loadLibrary("rxtxSerial")
val portList = CommPortIdentifier.getPortIdentifiers()
while (portList.hasMoreElements()) {
val x = portList.nextElement() as CommPortIdentifier
println("Port Name = " + x.name + ", type= " + x.portType)
}
if (portList.nextElement() == null) println("Is Null")
}
fun setDllLibraryPath(resourceStr: String) {
try {
System.setProperty("java.library.path", resourceStr)
//System.setProperty("java.library.path", "/lib/x64");//for example
val fieldSysPath =
ClassLoader::class.java.getDeclaredField("sys_paths")
fieldSysPath.isAccessible = true
fieldSysPath.set(null, null)//next time path is accessed, the new path
will be imported
} catch (ex: Exception) {
ex.printStackTrace()
throw RuntimeException(ex)
}
}https://stackoverflow.com/questions/51864751
复制相似问题