如何使用Kotlin从FIFO文件中读取字符

时间:2019-01-14 08:47:24

标签: java linux kotlin udev

我要做什么: 我正在尝试在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

1 个答案:

答案 0 :(得分:0)

我找到了正确的答案。 问题是找到第一个输入后我正在关闭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]