gpt4 book ai didi

java - 如何使用kotlin从fifo文件中读取字符

转载 作者:太空宇宙 更新时间:2023-11-04 11:56:32 24 4
gpt4 key购买 nike

我想做什么:我正在尝试将 Linux udev 和 Kotlin 结合起来。更确切地说,当我将 USB 插入我的 PC 时,udev 的规则之一将启动一个脚本,该脚本将向 FIFO 文件附加一些文本。 (如:add,003,026。其中 003 是总线号,026 是设备号)。现在在 Kotlin 端,我打算读取这些信息并将其显示到 IDE 控制台。这里一切都很好。

我的问题:当我因为只有一个插件而只收到一个事件时,一切正常。但是当我尝试插入多个设备时(通过按下连接了 7 个设备的集线器上的电源按钮),我通常只在 Kotlin 端接收到 3 个设备。即使 FIFO 文件具有所有值。

示例代码这是我最后一次尝试获取所有信息

fun main(args: Array<String>) {
println("Hello, World")
while(true) {
println("I had received this: " + readUsbState())
//println("Am primit inapoi: " + ins.read())
TimeUnit.SECONDS.sleep(1L)
}
}

@Throws(FileNotFoundException::class)
private fun readUsbState(): String {
if (!File("/emy/usb_events").exists()) {
throw FileNotFoundException("The file /emy/usb_events doesn't exists!")
}
val bytes = ByteArrayOutputStream()
var byteRead = 0
val bytesArray = ByteArray(1024)
try {
FileInputStream("/emy/usb_events").use { inputStream ->
byteRead = inputStream.read(bytesArray, 0, bytesArray.size)
if (byteRead >= 0) {
bytes.write(bytesArray, 0, byteRead)
}
}
} catch (ex: IOException) {
ex.printStackTrace()
}
return bytes.toString()
}

更多说明:我的 fifo 文件是“/emy/usb_events”。这个文件是用 mkfifo/emy/usb_events 创建的

为了让测试部分不必理会 udev 规则,您可以简单地执行 echo -e "add,001,001\nadd,001,002\nadd,001,003\n...">>/emy/usb_events

最佳答案

我找到了正确的答案。问题是我在找到第一个输入后关闭了 FIFO 文件。以下代码完美运行:

fun main(args: Array<String>) {
println("Hello, World")
while(true) {
println("I had received this: " + readUsbState4())
TimeUnit.SECONDS.sleep(1L)
}
}

private fun readUsbState4(): String {
return File("/certus/usb_events").readLines(Charset.defaultCharset()).toString()
}

在我收到的列表中,我可能有多个信息,例如:

Hello, World
I had received this: [add,046,003,4-Port_USB_2.0_Hub,Generic,]
I had received this: [add,048,003,Android_Phone,FA696BN00557,HTC, add,047,003,4-Port_USB_2.0_Hub,Generic,, add,049,003,DataTraveler_2.0,001BFC31A1C7C161D9C75AED,Kingston]
I had received this: [add,050,003,SAMSUNG_Android,06157df6cc9ac70e,SAMSUNG, add,053,003,SAMSUNG_Android,ce0416046d6a9e3f05,SAMSUNG, add,051,003,Acer_S57,0123456789ABCDEF,MediaTek, add,052,003,ACER_Z160,SKU4HI8L4L99N76H,MediaTek]
I had received this: [remove,048,003]
I had received this: [remove,051,003, remove,052,003, remove,049,003, remove,053,003, remove,050,003]
I had received this: [remove,047,003]
I had received this: [remove,046,003]

关于java - 如何使用kotlin从fifo文件中读取字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54178145/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com