首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >未使用usb4java标识COM端口

未使用usb4java标识COM端口
EN

Stack Overflow用户
提问于 2018-08-16 02:54:42
回答 1查看 304关注 0票数 0

我有以下例程,它是在windows中运行的usb4java应用程序接口中访问串行端口的入口点。任何想法都可能是错误的。

代码语言:javascript
复制
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来工作。我可以通过这个接口读取有效数据。

代码语言:javascript
复制
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();
      }
    }
}
EN

回答 1

Stack Overflow用户

发布于 2018-09-14 00:45:14

我发现javax.comm库并不是完全的implementedsupported。我觉得奇怪的是,像从串口读取这样的基本功能对Java来说是一项困难的任务,而托管web应用程序却被各种API重复。我希望串行通信在Python和C++中得到很好的支持,因为它们更多地被科学界使用。

我发现的另一个解决方案是利用RXTX API...onetwo。该过程包括下载压缩的发行版,并将dll和jar解压到FileSystem上的某个库站点。然后声明对Jar文件的依赖关系。例如在Gradle中

compile files( 'C:/..path../lib/jars/RXTXcomm.jar')

设置dll库路径并加载dll

代码语言:javascript
复制
System.setProperty("java.library.path", "C:/..path../lib/dlls_x64")
System.loadLibrary("rxtxSerial")

最后,串行接口不在javax.comm包中,而是在gnu.io包中。

代码语言:javascript
复制
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)
  }
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/51864751

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档